My solution is below


  • 1
    Y
    class Solution {
    public:
        int titleToNumber(string s) {
    		int result = 0;
    		for (int i = s.size() - 1; i >= 0; i--)
    			result += (s[i] - 'A' + 1) * pow(26, s.size() - 1 - i);
    		return result;
        }
    };

  • 0

    Hey, here is my solution, I think we have the same idea, is there a better solution?

    public int titleToNumber(String s) {
        if(s == null || s.length() <= 0){
            return 0;
        }
        byte[] b = s.getBytes();
        int sum = 0;
        for(int i = 0 ; i < b.length ; i++){
            sum += (b[i] - 64)*Math.pow(26, b.length - i - 1);
        }
        return sum;
    }
    

  • 0
    Y

    I like intuitive solution, because it can be understood easily, maybe it is not a better solution. The solution using too much skills is more difficult to understand than common solution.


  • 0
    I

    Hi, I have the same habit to check some special cases in the begin, like s ==null.
    But I don't get it why there is also "s.length() <= 0". Could you explain that, maybe give me some examples? Thanks a lot!


  • 0

    If the parameter s is equal to "",the result will be what ?


  • 0
    I

    yes, it explains s.length() = 0, now what about the situation where the length is less than 0?
    Thanks


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.