首页 > 代码库 > [leetcode] Excel Sheet Column Title & Excel Sheet Column Number

[leetcode] Excel Sheet Column Title & Excel Sheet Column Number

Excel Sheet Column Title

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进制转2进制一样。

题解:

技术分享
class Solution {public:    string convertToTitle(int n) {        string res;        while(n) {            n -= 1;            char c = n%26+A;            res = c+res;            n /= 26;        }        return res;    }};
View Code

Excel Sheet Column Number

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进制,与2进制转10进制一样。

题解:

技术分享
class Solution {public:    int titleToNumber(string s) {        int res = 0;        for(int i=0;i<s.size();i++) {            char c = s[i];            int tmp = c-A+1;            res = res*26+tmp;        }        return res;    }};
View Code

 

[leetcode] Excel Sheet Column Title & Excel Sheet Column Number