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

For example:

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

 

思路:

相当于10进制转26进制。与一般不一样的是10进制对应的是0 - 9。而这个26进制对应的是 A(1)- Z(26), 没有0。

我的代码:

string convertToTitle(int n) {
        string ans;
        while(n != 0)
        {
            int num = n % 26;
            n /= 26;
            if(num != 0)
            {
                ans.push_back(num - 1 + 'A');
            }
            else
            {
                ans.push_back('Z');
                n--;
            }
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }

大神精简的代码:

string convertToTitle(int n) {
    string res;
    char tmp;
    while(n){
        n -= 1; //这里相当于把A-Z表示成了0-25就与一般的表达一样了
        tmp = 'A' + n % 26;
        res = tmp + res;
        n /= 26;
    }
    return res;
}

 

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 

 

思路:26进制转10进制。 以AAA为例   AAA = A * 26+ A * 261 + A * 260

int titleToNumber(string s) {
        int ans = 0;
        int factor = 1;
        while(!s.empty())
        {
            ans = ans + (s.back() - 'A' + 1) * factor;
            s.pop_back();
            factor *= 26;
        }
        return ans;
    }

大神精简版的:

int result = 0;
for (int i = 0; i < s.size(); result = result * 26 + (s.at(i) - 'A' + 1), i++);
return result;