首先这道题的链接:https://leetcode.com/problems/excel-sheet-column-title/
一开始没有太大的思路的同学可以和我一样尝试着先写出,将一个10进制数按位输出为一个string:
代码如下:
int main(){
int n=10123;
string result;
while (n) {
result=(char)(n%10+'0')+result;
n/=10;
}
cout<<result<<endl;
}
那么仿照上面的代码,我们即可写出这道题的一个类似写法:
代码如下:
int main(){
int n=1;
string result;
while (n) {
result=(char)(n%26+'A')+result;
n/=26;
}
cout<<result<<endl;
}
但是这样是不对的,
因为我们正常的十进制体系是,每一位都处在0-9之间,
而题目中要求的26进制体系是,每一位都处在1-26之间,
那么为了回归我们正常的体系,也就是第一种代码,
我们需要将每一位都-1操作,得到正确的代码:
class Solution {
public:
string convertToTitle(int n) {
string result="";
while (n) {
--n;
result=(char)(n%26+'A')+result;
n/=26;
}
return result;
}
};