美文网首页
168. Excel Sheet Column Title

168. Excel Sheet Column Title

作者: YellowLayne | 来源:发表于2017-06-22 18:01 被阅读0次

1.描述

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 

2.分析

3.代码一

class Solution {
public:
    string convertToTitle(int n) {
        if (n <= 0) return "";
        string title = "";
        while (n > 26) {
            unsigned int remaind = n % 26;
            title.insert(title.begin(), remaind > 0 ? 'A' + n % 26 -1 : 'Z');
            n /= 26;
            n -= remaind > 0 ? 0 : 1;
        }
        unsigned int remaind = n % 26;
        title.insert(title.begin(), remaind > 0 ? 'A' + n % 26 -1 : 'Z');
        return title;
    }
};

4.代码二

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

相关文章

网友评论

      本文标题:168. Excel Sheet Column Title

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