高精度进制转换

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

int val(char c) { // 字符转值
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
    return c - 'a' + 36;
}

char digitChar(int v) { // 值转字符
    if (v < 10) return '0' + v;
    if (v < 36) return 'A' + (v - 10);
    return 'a' + (v - 36);
}

void mul(vector<int>& a, int m) { // 高精乘
    int carry = 0;
    for (int i = 0; i < (int)a.size(); i++) {
        int t = a[i] * m + carry;
        a[i] = t % 10;
        carry = t / 10;
    }
    while (carry) {
        a.push_back(carry % 10);
        carry /= 10;
    }
}

void add(vector<int>& a, int v) { // 高精加
    int carry = v;
    for (int i = 0; i < (int)a.size(); i++) {
        int t = a[i] + carry;
        a[i] = t % 10;
        carry = t / 10;
        if (!carry) return;
    }
    while (carry) {
        a.push_back(carry % 10);
        carry /= 10;
    }
}

int mod(vector<int>& a, int d) { // 高精取模
    int r = 0;
    for (int i = (int)a.size() - 1; i >= 0; i--) {
        int t = r * 10 + a[i];
        a[i] = t / d;
        r = t % d;
    }
    while (a.size() > 1 && a.back() == 0)
        a.pop_back();
    return r;
}

int main() {
    ios::sync_with_stdio(0),cin.tie(0);
    int x, y;
    string z;
    cin >> x >> y >> z;

    vector<int> value(1, 0);

    // x进制转十进制
    for (char c : z) {
        int d = val(c);
        mul(value, x);   // value = value * x
        add(value, d);   // value += d
    }

    if (value.size() == 1 && value[0] == 0) {// 特判0
        cout << 0;
        return 0;
    }

    // 十进制转y进制
    string out;
    while (!(value.size() == 1 && value[0] == 0)) {
        int r = mod(value, y);   // value % y, value /= y 
        out.push_back(digitChar(r));
    }

    reverse(out.begin(), out.end());
    cout << out;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值