Java 3ms O(N) Solution


  • 1
    R

    Example:

    "BAA" --> 2 * 26^2 + 1 * 26^1 + 1 * 26^0
    "ZBAC" --> 26 * 26^3 + 2 * 26^2 + 1 * 26^1 + 3 * 26^0 
    

    Code:

    public int titleToNumber(String s) {
    		if (s == null)
    			return 0;
    		int result = 0;
    		int j = 0;
    		for (int i = s.length() - 1; i >= 0; i--) {
    			int c = (int)s.charAt(i) - 64; 
    			result += c * (int)Math.pow(26, j);
    			j++;
    		}
    		return result;
    	}

  • 1

    If people use for(int i = 0; i < s.length(); i++), they don't need to let s.charAt(i) to be int. Why at your situation, you should let s.charAt(i) to be int?


Log in to reply
 

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