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首先算出多少位,再把小于这个位数的字符串数目删掉,最后就相当于26进制转换。
class Solution {
public:
string convertToTitle(int n) {
string ans;
int b[10] = {1};
int sum[10] = {0};
sum[0] = 26;
int m = n, i = 0;
while(double(b[i]) < m / 26.0){
b[i + 1] = b[i] * 26;
++i;
m -= b[i];
sum[i] = sum[i - 1] + b[i] * 26;
}
if(i > 0) n -= sum[i - 1];
while(i > 0){
int t = (n - 1) / b[i];
n = n - t * b[i];
ans += char(t + 65);
i--;
}
ans += char(n + 64);
return ans;
}
};
更简单的:
class Solution {
public:
string convertToTitle(int n) {
string res = "";
while(n)
{
res = (char)('A' + (n-1)%26) + res;
n = (n-1) / 26;
}
return res;
}
};