ZJANS

c665. 進制轉換

Medium Last Update: 2026/01/22
基本運算

解法一

✅ 完整代碼

評分結果(參考) : AC (5ms, 316KB)

#include<bits/stdc++.h>
#define int long long
using namespace std;

int s2i(string& s, int b1){
    int res = 0;
    for(char c : s){
        res = b1*res + ((c>'9') ? c-'A'+10 : c-'0');
    }
    return res;
}

string i2s(int num, int b2) {
    if(num == 0) return "0";
    
    string s;
    while(num > 0) {
        s.push_back((num%b2)>9 ? 'A'+(num%b2)-10 : '0'+(num%b2));
        num /= b2;
    }
    
    reverse(s.begin(), s.end());
    return s;
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string n;
    int b1, b2;
    while(cin >> n >> b1 >> b2){
        int num = s2i(n, b1);
        cout << i2s(num, b2) << '\n';
    }
}