首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

NYOJ 303 序號互換:Excel 列名與數字雙向轉換(26 進制變體)

     編輯:C++ 入門

問題描述

Excel 欄位編號規則:1→A, 2→B, ..., 26→Z, 27→AA, 28→AB... 給定數字或字母序號,實現雙向轉換。數字 ≤ 2×10⁹。

核心洞察:無「0」的 26 進制

普通 26 進制有 0~25,但此處 A=1, Z=26,**無 0 的表示**。轉換關鍵:每次取模前先減 1。

數字 → 字母(10 進制轉 26 進制無零制)

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"

字母 → 數字(26 進制無零制轉 10 進制)

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 夠,但轉換中間值可能更大)
  • 字符串長度最多 log₂₆(2×10⁹) ≈ 7 位,char ans[20] 足夠
  • **必須先減 1 再取模**,否則 26 會變成 'Z' 但進位錯誤

總結

Excel 列名轉換是「無零 26 進制」的經典應用。記住口訣:**數轉字「先減一」,字轉數「加一算」**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved