思路:
通过读题我们可以发现,题面是让我们将一个数字转换为类似Excel列名的字符串。
但我们的数字是十进制的,而字母有二十六个,也就是二十六进制。
所以我们就要考虑进行进制转换,也就是执行上面的操作。
while (n > 0) {
n--;//保证n每次是从0开始,而不是1
int letter = n % 26;
ans = char ( 'a' + letter ) + ans ;
n = n / 26;
}上面的 循环就是本题的核心代码。
我们不妨模拟一下:
假设输入的 为 。
代入该 循环后:
- ,循环结束
那么思想成立,代码实现!
Code:
#include <bits/stdc++.h>
using namespace std;
#define int long long
string func(int n) {
string ans = "" ;//字符串一定先清空
while (n > 0) {
n--;
int letter = n % 26;
ans = char ( 'a' + letter ) + ans ;
n = n / 26;
}
return ans;
}
signed main() {
int n;
cin >> n;
cout << func(n) << endl;
return 0;
}