2026年1月25日 星期日

ZeroJudge 解題筆記:c009. 10473 - Simple Base Conversion

作者:王一哲
日期:2026年1月25日


ZeroJudge 題目連結:c009. 10473 - Simple Base Conversion

解題想法


這題如果用 Python 寫很簡單,可以用內建的工具 int(字串, 基底) 將字串以指定的基底轉換成十進位整數,也可以用 hex(整數) 將十進位整數轉換成 16 進位制字串。如果用 C++ 解題則需要自己寫轉換用的函式。

Python 程式碼


使用時間約為 7 ms,記憶體約為 2.8 MB,通過測試。
import sys

for s in sys.stdin:
    s = s.rstrip()
    if s[0] == "-": break
    elif s[:2] == "0x":
        print(int(s[2:], 16))
    else:
        t = hex(int(s))[2:].upper()
        print("0x" + t)

使用時間約為 9 ms,記憶體約為 2.9 MB,通過測試。
import sys

result = []
lines = sys.stdin.readlines()
for s in lines:
    s = s.strip()
    if not s: continue
    if s[0] == "-": break
    elif s[:2] == "0x":
        result.append(f"{int(s[2:], 16):d}\n")
    else:
        t = hex(int(s))[2:].upper()
        result.append(f"0x{t}\n")
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 1 ms,記憶體約為 320 kB,通過測試。
#include <iostream>
#include <string>
#include <map>
using namespace std;

int hex_to_dec(string s) {
    int base = 1, result = 0;
    map<char, int> nums = 
        {{'0', 0}, {'1', 1}, {'2', 2}, {'3', 3},
         {'4', 4}, {'5', 5}, {'6', 6}, {'7', 7}, 
         {'8', 8}, {'9', 9}, {'A', 10}, {'B', 11}, 
         {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}; 
    for(auto it = s.rbegin(); it != s.rend(); it++) {
        result += nums[*it]*base;
        base *= 16;
    }
    return result;
}

string dec_to_hex(int n) {
    string s = "";
    map<int, char> nums = 
        {{0, '0'}, {1, '1'}, {2, '2'}, {3, '3'},
         {4, '4'}, {5, '5'}, {6, '6'}, {7, '7'},
         {8, '8'}, {9, '9'}, {10, 'A'}, {11, 'B'},
         {12, 'C'},  {13, 'D'}, {14, 'E'}, {15, 'F'}};
    while(n > 0) {
        s = nums[n%16] + s;
        n /= 16;
    }
    return "0x" + s;
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string s;
    while(cin >> s) {
        if (s[0] == '-') break;
        else if (s.substr(0, 2) == "0x") cout << hex_to_dec(s.substr(2)) << "\n";
        else cout << dec_to_hex(stoi(s)) << "\n";
    }
    return 0;
}


沒有留言:

張貼留言