Excel Sheet Column Number

Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 

迭代的方法

class Solution {
public:
    int titleToNumber(string s) {

        int res = 0;
        for(int i = 0; i < s.size(); i++){
            res = (int)(s[i] - 'A' + 1) + 26 *res; 
        }
        return res;
    }
};

递归的方法

class Solution {
public:
    int titleToNumber(string s) {
        return s.empty() ? 0 : 26*titleToNumber(s.substr(0, s.size() - 1)) + ((int)(s.back() - 'A') + 1);
    }
};

results matching ""

    No results matching ""