A 8ms C++ Solution


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

  • 0
    T

    An alternative solution: from left to right to calculate the value of string s. e.g:
    "AB" = ('A'-'A'+1) * 26 + ('A'-'B'+1)

    class Solution {
    public:
        int titleToNumber(string s) {
            int result = 0;
            for (auto c : s) {
                result = result*26 + (c - 'A' + 1);
            }
            return result;
        }
    };
    

  • 0
    A

    @tianhongbo1 according to your equation, the ''AB'' string equals 26. Its actual value is 28. Please correct for this


  • 0
    D

    @yuming.wei Using "pow" method every time in the loop is making your solution slow. You can easily avoid it.

    Here's my 3ms C++ code.

    int titleToNumber(string s) {
            int cnum = 0;
            for(int i = 0; i < s.length(); i++){
                cnum *= 26;
                cnum += s[i] - 'A' + 1;
            }
            return cnum;
    }
    

  • 0
    M

    @ddeveshh the same to you,but mine is 6ms ,why


Log in to reply
 

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