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
难度EASY。相当于是26进制转换,稍微做点处理。
class Solution {
public:
string convertToTitle(int n) {
string s = "";
while(n)
{
int x = --n % 26;
s += 'A' + x;
n /= 26;
}
reverse(s.begin(),s.end());
return s;
}
};
还有一种更简单的写法,避免用Reverse,直接利用递归栈的思想。
如下:
class Solution {
public:
string convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(n / 26) + (char) (--n % 26 + 'A');
}
};