問題
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
分析
簡(jiǎn)單的字符映射,每次循環(huán)將數(shù)字除26減1然后求對(duì)26的余數(shù)再轉(zhuǎn)成A-Z即可。
要點(diǎn)
字符映射,注意1、26、27等邊界情況。
時(shí)間復(fù)雜度
O(logn)
空間復(fù)雜度
O(1)
代碼
class Solution {
public:
string convertToTitle(int n) {
string res;
while (n--) {
res = (char)('A' + n % 26) + res;
n /= 26;
}
return res;
}
};