3ms solution using ASCII values in C++


  • 0
    L

    There are two key points to keep in mind for this problem.

    1. ASCII value of A is 65.
    2. The number goes in base 26.
      Using point 1) to get the correct value when char is cast into integer should minus 64.
      Using point 2) pow(26, s.length() -i -1) gives the correct base 26 value.
      For example:
      A = 1 -> 26^(0);
      AA = 27 -> 26^1 + 26^0;
      and so on.

    Add them up we'll get the result.

    public:
        int titleToNumber(string s) {
            int result = 0;
            for(int i=0; i<s.length(); i++){
                result += (s[i] - 64)*pow(26, s.length()-i-1); 
            }
            return result;
        }
    };
    

Log in to reply
 

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