美文网首页
168 Excel Sheet Column Title

168 Excel Sheet Column Title

作者: Shiyi001 | 来源:发表于2016-10-16 10:47 被阅读0次

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

For example:
<pre>
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
</pre>


解题思路

这道题是171的逆向问题,但是个人感觉比171要难一些。

之前由171题分析可知,此题类似于“26进制”。但是与一般n进制不同的是,该“26进制”没有0(没有字母能代表0),却有26(相当于n进制中的n)。所以我们在做进制转换的时候,如果遇到模除为0的情况,可以考虑向前面“借”一位,将0变为26(也就是把‘A’变成‘Z’),其他情况与一般进制转换相同。


代码

class Solution {
public:
    string convertToTitle(int n) {
        string res = "";
        
        while (n>0){
            int x = n%26;
            if (x == 0){
                res += 'Z'; n = n-26;//向前面借一位
            }else{
                res += exchange(x);
            }
            n /= 26;
        }
        
        int len = res.length();
        for (int i=0;i<len/2;i++){
            swap(res[i],res[len-i-1]);
        }
        return res;
    }
    
    char exchange(int x){
        return 'A'+x-1;
    }
};

相关文章

网友评论

      本文标题:168 Excel Sheet Column Title

      本文链接:https://www.haomeiwen.com/subject/ylioyttx.html