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
这道题的要求是将整数转化成Excel表格中相对应的列标题。
可以注意到,1转化成A,2转化成B,等等,转换后是26进制,而且是由原先没有0的十进制转化过去的,因此,每次均需要对整数进行减1处理,这样就可以直接模26求出对于数位的字母了。
时间复杂度:O(n)
空间复杂度:O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution
{
public:
string convertToTitle(int n)
{
string s = "";
while(n -- > 0)
{
s = (char) (n % 26 + 'A') + s;
n /= 26;
}
return s;
}
};
当然,递归的话,可以看到代码更简短,只剩下1行了。。。
1
2
3
4
5
6
7
8
class Solution
{
public:
string convertToTitle(int n)
{
return n == 0 ? "" : convertToTitle((n - 1) / 26) + (char)((n - 1) % 26 + 'A');
}
};