题目:
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中对应的列号。如上面所示,这是一个26进制的转换。
思路:
采用递归的方法,当前数字的模26就是该位置对应的数字,而当前数字除26是该位置之前对应的结果,把之前的结果拼接上这个位置的结果就是最终结果。因为需要先计算前面的结果,所以采用递归的方法。
代码如下:
class Solution {
public:
string convertToTitle(int n) {
if(n == 0)return "";
string result = "";
if(n > 26)
{
result = convertToTitle( (n - 1)/26);
}
result.push_back('A' + (n - 1) % 26);
return result;
}
};