梦熊2025 -- 星航计划 -- 三月份 -- 基础语法T2-命名 题解

· · 题解

梦熊原题

思路:

通过读题我们可以发现,题面是让我们将一个数字转换为类似Excel列名的字符串。

但我们的数字是十进制的,而字母有二十六个,也就是二十六进制。

所以我们就要考虑进行进制转换,也就是执行上面的操作。

while (n > 0) {
    n--;//保证n每次是从0开始,而不是1
    int letter = n % 26;
    ans = char ( 'a' + letter ) + ans ;
    n = n / 26;
}

上面的 while 循环就是本题的核心代码。

我们不妨模拟一下:

假设输入的 n 为 28 。

代入该 while 循环后:

  1. 28 - 1 = 27
  2. 27 \% 26 = 1
  3. ans = 'a' + 1 + '' = 'b'
  4. 27 / 26 = 1
  5. 1 - 1 = 0
  6. 0 \% 26 = 0
  7. ans = 'a' + 0 + 'b' = 'ab'

那么思想成立,代码实现!

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;
}