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 

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


根十进制转换成二进制一样,

789=1100010101

789/2=394.5 =1 第10位

394/2=197 =0 第9位

197/2=98.5 =1 第8位

98/2=49 =0 第7位

49/2=24.5 =1 第6位

24/2=12 =0 第5位

12/2=6 =0 第4位

6/2=3 =0 第3位

3/2=1.5 =1 第2位

1/2=0.5 =1 第1位[1]

这里是/26,取26的余数, 注意是转换是从1开始计数的,不是从0开始的,所以不是直接地做26进制转换那么简单,因此要减一操作。

就像是26的时候,转换成字母形式,是Z,如果直接%26,结果是0+‘A'='A',所以在进行计算的时候,n=(n-1)/26; (n-1)%26=25+'A'='z'

 52->AZ

class Solution {
public:
    string convertToTitle(int n) {
        string result="";
        while(n){
            result=(char)((n-1)%26+'A')+result;
            n=(n-1)/26;
        }
        return result;
    }
};


你可能感兴趣的:(Excel Sheet Column Title)