3ms Java solution


  • 1
    V

    public class Solution {

    public int titleToNumber(String s) {
        char[] charArray = s.toCharArray();
        int factor = 1;
        int result = 0;
        for(int i = s.length() - 1; i >= 0; i--) {
            result += (charArray[i] - 'A' + 1) * factor;
            factor *= 26;
        }
        return result;
    }
    

    }


  • 1
    A

    I suggest doing s.charAt(i) instead of creating a char array. Since java Strings are technically char arrays (private final char value[];), you'd save more space.

    EDIT:
    You could further improve it by getting rid of factor and using Math.pow(). Math.pow() is more efficient.

    for(int i = 0; i < s.length(); i++){
        result += (s.charAt(s.length() - 1 - i) - 'A' + 1) * Math.pow(26,i);
    }

Log in to reply
 

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