Problem:
给一个数字,输出对应的字母编号,1-A, 26-Z,27-AA。
Solution:
考察的是进制的转换,难点在于对于26的倍数的处理,通过取余时-1然后再+1来实现。
Solution1:
class Solution {
public:
string convertToTitle(int n) {
return (n==0) ? "" : convertToTitle((n-1)/26) + char('A'+(n-1)%26);
}
};
Solution2:
class Solution {
public:
string convertToTitle(int n) {
string ans;
while(n) {
ans = char((n-1)%26 +'A') + ans;
n = (n-1)/26;
}
return ans;
}
};