日期:2025年8月20日
ZeroJudge 題目連結:c665. 進制轉換
解題想法
先建立兩個對照表,table 是串列格式,用來找出 0 ~ 35 對應的字元;val 是字典格式,用來找出 0 ~ 35 字元對應的數值。用自訂函式 convert,將 a 進位制的字串 s 先轉換成 10 進位制的整數 d,再將 d 轉換成 b 進位制的字串 t。
Python 程式碼
使用時間約為 25 ms,記憶體約為 3.6 MB,通過測試。
import sys
# 0 ~ 35 對應的字元表格
table = [str(i) for i in range(10)]
for i in range(26): table.append(chr(i+ord('A')))
# 0 ~ 35 字元對應的數值
val = dict()
for i in range(10): val[str(i)] = i
for i in range(26): val[chr(i+ord('A'))] = i+10
# 主要的解題過程,a 進位制字串 s,轉成 b 進位制
def convert(s, a, b):
d = 0 # 10 進位制的數字
base = 1 # a 進位制基底
for c in s[::-1]: # 依序讀取 s[-1] ~ s[0]
d += val[c]*base # 更新 d
base *= a # 更新 base
t = "" # 儲存轉換後結果的空字串
while d: # 如果 d 大於 0 繼續執行
t = table[d%b] + t # d%b 代入 table 找出對應的字元
d //= b # 更新 d
return t # 回傳 t
for line in sys.stdin:
n, b1, b2 = line.split()
b1 = int(b1); b2 = int(b2)
print(convert(n, b1, b2))
C++ 程式碼
使用時間約為 4 ms,記憶體約為 340 kB,通過測試。
#include <iostream>
#include <string>
#include <map>
using namespace std;
char table[36]; // // 0 ~ 35 對應的字元表格
map<char, int> val; // 0 ~ 35 字元對應的數值
/* 主要的解題過程,a 進位制字串 s,轉成 b 進位制 */
string convert(string s, int a, int b) {
int d = 0, base = 1; // 10 進位制的數字,a 進位制基底
for(auto it = s.crbegin(); it != s.crend(); it++) { // 依序讀取 s[-1] ~ s[0]
d += val[*it]*base; // 更新 d
base *= a; // 更新 base
}
string t = ""; // 儲存轉換後結果的空字串
while(d) { // 如果 d 大於 0 繼續執行
t = table[d%b] + t; // d%b 代入 table 找出對應的字元
d /= b; // 更新 d
}
return t; // 回傳 t
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
/* 建立轉換字元及數值的表格 */
for(int i=0; i<10; i++) {
table[i] = char(i+'0');
val[char(i+'0')] = i;
}
for(int i=0; i<26; i++) {
table[i+10] = char(i+'A');
val[char(i+'A')] = i+10;
}
/* 讀取資料,代入 convert 求解 */
string n; int b1, b2;
while(cin >> n >> b1 >> b2) cout << convert(n, b1, b2) << "\n";
return 0;
}
沒有留言:
張貼留言