原题链接

将一个 a 进制数转换成一个 b 进制数。思路在于模拟一个 a 进制数直接对一个十进制数 b 做除法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;
#include <algorithm>

int n;

int main() {
cin >> n;
while (n--) {
int a, b;
string a_line, b_line;
cin >> a >> b >> a_line;
vector<int> num;
for (auto &x : a_line) {
if (x >= 'A' && x <= 'Z') {
num.push_back(x - 'A' + 10);
} else if (x >= 'a' && x <= 'z') {
num.push_back(x - 'a' + 36);
} else {
num.push_back(x - '0');
}
}
reverse(num.begin(), num.end());
vector<int> res;
while (num.size()) {
int r = 0;
for (int i = num.size() - 1; i >= 0; i--) {
num[i] += r * a;
r = num[i] % b;
num[i] /= b;
}
res.push_back(r);
while (num.size() && num.back() == 0) num.pop_back();
}
reverse(res.begin(), res.end());
for (auto &x : res) {
if (x <= 9) b_line += char(x + '0');
if (x >= 10 && x <= 35) b_line += char(x - 10 + 'A');
if (x >= 36) b_line += char(x - 36 + 'a');
}
cout << a << ' ' << a_line << endl;
cout << b << ' ' << b_line << endl;
cout << endl;
}
return 0;
}