Excel 欄位編號規則:1→A, 2→B, ..., 26→Z, 27→AA, 28→AB... 給定數字或字母序號,實現雙向轉換。數字 ≤ 2×10⁹。
普通 26 進制有 0~25,但此處 A=1, Z=26,**無 0 的表示**。轉換關鍵:每次取模前先減 1。
while (n > 0) {
n--; // 關鍵:先減 1
char c = 'A' + n % 26; // 取餘
ans.push_back(c);
n /= 26;
}
reverse(ans); // 低位在前,需反轉
例:27 → n=27, n--=26, 26%26=0→'A', n=1; n--=0, 0%26=0→'A' → "AA"
long long ans = 0;
for (char c : s) {
ans = ans * 26 + (c - 'A' + 1); // A=1, B=2...
}
例:"AA" → 1×26+1 = 27
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
void numToStr(char *s) {
long long n = 0;
for (int i = 0; s[i]; i++) n = n * 10 + s[i] - '0';
char ans[20]; int top = 0;
while (n) {
n--;
ans[top++] = 'A' + n % 26;
n /= 26;
}
for (int i = top - 1; i >= 0; i--) putchar(ans[i]);
putchar('\n');
}
void strToNum(char *s) {
long long ans = 0;
for (int i = 0; s[i]; i++) ans = ans * 26 + s[i] - 'A' + 1;
printf("%lld\n", ans);
}
int main() {
int T; char s[20];
scanf("%d", &T);
while (T--) {
scanf("%s", s);
if (s[0] >= '0' && s[0] <= '9') numToStr(s);
else strToNum(s);
}
return 0;
}
long long(≤ 2×10⁹ 其實 int 夠,但轉換中間值可能更大)char ans[20] 足夠Excel 列名轉換是「無零 26 進制」的經典應用。記住口訣:**數轉字「先減一」,字轉數「加一算」**。