168. Excel Sheet Column Title

2017-05-06  本文已影响0人  RobotBerry

问题

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

例子

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

分析

简单的字符映射,每次循环将数字除26减1然后求对26的余数再转成A-Z即可。

要点

字符映射,注意1、26、27等边界情况。

时间复杂度

O(logn)

空间复杂度

O(1)

代码

class Solution {
public:
    string convertToTitle(int n) {
        string res;
        while (n--) {
            res = (char)('A' + n % 26) + res;
            n /= 26;
        }
        return res;
    }
};
上一篇下一篇

猜你喜欢

热点阅读