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

[LeetCode] Excel Sheet Column Title 求Excel表列名称

时间:2015-01-16 07:36:22      阅读:155      评论: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.

 

此题和Excel Sheet Column Number 求Excel表列序号是一起的,但是我在这题上花的时间远比上面一道多,起始原理都一样,就是一位一位的求,此题从低位往高位求,每进一位,则把原数缩小26倍,再对26取余,之后减去余数,再缩小26倍,以此类推,可以求出各个位置上的字母。最后只需将整个字符串翻转一下即可。 代码如下:

 

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

 

[LeetCode] Excel Sheet Column Title 求Excel表列名称

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4227618.html

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