--- 这里是 cjiaw 的小窝(●'◡'●) ---

正在玩命加载中......

AcWing 124. 数的进制转换(进制转换)

题目链接:124. 数的进制转换 - AcWing题库


题目大意:

编写一个程序,可以实现将一个数字由一个进制转换为另一个进制。

这里有 62 个不同数位 {09,AZ,az}


思路:

每次循环完成一次"整个数 ÷ b"的操作,余数就是结果的一位数字,最后翻转在转成字符就是答案


代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define  mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;

const int N = 200086, mod = 998244353;

int a, b;
string s;

int toint(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    else if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
    else return c - 'a' + 36;
}

char tochar(int c) {
    if (c >= 0 && c <= 9) return c + '0';
    else if (c >= 10 && c < 36) return c + 'A' - 10;
    else return c + 'a' - 36;
}

void solve() {

    cin >> a >> b >> s;
    vector<int> num, res;
    for (int i = 0; i < s.size(); i++) {
        num.push_back(toint(s[i]));
    }
    
    reverse(num.begin(), num.end());
    
    while (num.size()) {
        int x = 0;//进位
        for (int i = num.size() - 1; i >= 0; i--) {
            num[i] += x * a;//进位
            x = num[i] % b;//给下一个进位
            num[i] /= b;
        }
        while (num.size() && !num.back()) num.pop_back();//清空后面的0
        res.push_back(x);//答案是对进制取模
    }
    
    reverse(res.begin(), res.end());
    cout << a << " " << s << endl << b << " ";
    for (auto x : res) cout << tochar(x);
    cout << endl << endl;
    
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    int T = 1;
    cin >> T;
    while (T--) solve();
    
    return 0;
}

 

posted @ 2025-11-01 17:28  wwjjw  阅读(17)  评论(0)    收藏  举报