Leetcode168. Excel表列名称

2019-11-10  本文已影响0人  LonnieQ

题目

给定一个正整数,返回它在 Excel 表中相对应的列名称。

例如,

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB 
...

示例 1:

输入: 1
输出: "A"

示例 2:

输入: 28
输出: "AB"

示例 3:

输入: 701
输出: "ZY"

C++解法

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    string convertToTitle(int n) {
        string result;
        do {
            --n;
            result.push_back('A' + n % 26);
        } while (n /= 26);
        reverse(result.begin(), result.end());
        return result;
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    Solution solution;
    for (int i = 1; i < 100; i++) {
        cout << solution.convertToTitle(i) << endl;
    }
    return 0;
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/excel-sheet-column-title

上一篇 下一篇

猜你喜欢

热点阅读