码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]62. Excel Sheet Column Title Excel列序号

时间:2015-11-06 19:29:55      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Subscribe to see which companies asked this question

 

解法:和Excel Sheet Column Number相反,这次是10进制转26进制。从低位往高位求,每进一位,则把原数缩小26倍,再对26取余,之后减去余数,再缩小26倍,以此类推,可以求出各个位置上的字母。最后只需将整个字符串翻转一下即可。

class Solution {
public:
    string convertToTitle(int n) {
        string res = "";
        while (n > 0) {
            int rem = n % 26;
            if (rem == 0) {
                res += "Z";
                n -= 26;
            }
            else {
                res += (char)(rem - 1 + A);
                n -= rem;
            }
            n /= 26;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

 

[LeetCode]62. Excel Sheet Column Title Excel列序号

标签:

原文地址:http://www.cnblogs.com/aprilcheny/p/4943404.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!