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 ...
Example 1:
Input: 1 Output: "A"
分析:
给定一个整数,返回相应的字母组合。相当于26进制,若不是26的整数倍,从低位往高位求,每进一位,则把原数缩小26倍,再对26取余,之后减去余数,再缩小26倍,最后只需将整个字符串翻转一下即可;如果是26的整数倍的话,直接加倍数个‘Z’即可。
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;
}
};