Transform the decimal number into a 26-scale number. Take care of the case that the number after mod is 0. Also, when the number is very big, long long will be needed.
class Solution {
public:
string convertToTitle(int n) {
string res;
long long num=n;
long long divider=1;
while(num)
{
long long a=(num%(divider*26))/divider;
if(!a)
a=26;
res+=a+'A'-1;
num-=a*divider;
divider*=26;
}
reverse(res.begin(),res.end());
return res;
}
};
Updated version:
class Solution {
public:
string convertToTitle(int n) {
string res;
while(n)
{
n--;
res+=n%26+'A';
n=n/26;
}
reverse(res.begin(),res.end());
return res;
}
};