1. 程式人生 > >[LeetCode] Excel Sheet Column Number 求Excel表列序號

[LeetCode] Excel Sheet Column Number 求Excel表列序號

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 

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

這題實際上相當於一種二十六進位制轉十進位制的問題,並不難,只要一位一位的轉換即可。程式碼如下:

class Solution {
public:
    int titleToNumber(string s) {
        int n = s.size();
        int res = 0;
        int tmp = 1;
        for (int i = n; i >= 1; --i) {
            res += (s[i - 1] - 'A' + 1) * tmp; 
            tmp *= 26;
        }
        return res;
    }
};