b197簡單

97 雲嘉區資訊學科能力競賽(2008)|十六進位轉十進位

由左到右處理每個十六進位字元,數字0至9取0至9,A至F取10至15。

解題思路

由左到右處理每個十六進位字元,數字0至9取0至9,A至F取10至15。

目前值乘16再加上新位數,即更新為讀入前綴所代表的數值。

使用任意精度整數,保留原十六進位字串並輸出累積值,前導零只保留在原字串欄。

長度L時 O(L)次大整數乘小整數與加法,位元成本 O(L²),空間 O(L)。

Step-by-step animation

教學小例:十六進位的Horner累積

回報動畫錯誤
步驟 1 / 3

字串00FF

前兩碼累積為0

前兩碼累積為0
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
int main() {
    string s;
    while (cin >> s) {
        cpp_int n = 0;
        for (char c : s)
            n = n * 16 + (c <= '9' ? c - '0' : c - 'A' + 10);
        cout << s << ' ' << n << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多