You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
//单个字母转换成数字 0-F
int char_to_int(char a) {
return '0' <= a && a <= '9' ? a - '0' : 10 + a - 'A';
}
//0-15之间的数字转为16进制的数字
char int_to_char(int a) {
return a <= 9 ? '0' + a : a - 10 + 'A';
}
int n; //原始的n进制
int m; //要转换成的m进制
string input; //输入的原始数字
int d; //原始数转为十进制的数字是多少,这是一个中间过程
vector<int> output; //用一个数字数组
/**
* 测试用例:
16 FF 2
答案: 11111111
测试用例2
15 5CBD1460 2
答案:
111011100110101100100111110110
*/
int main() {
//题意将输入的n进制数input转为m进制
cin >> n >> input >> m;
//原数转换为十进制,从左向右噢
for (int i = 0; i < input.size(); i++)//遍历输入字符串的每一位一边转每一位是十进制一边乘n累加得到换算后的十进制数。
d = d * n + char_to_int(input[i]);//秦九韶算法,就是迭代方式提高效率
//输出测试一下:255
//cout << d << endl;
//将十进制数转换为m进制数的每一位是多少
while (d) output.push_back(d % m), d /= m;//一路取余保存,得到一个反向的数字序列。学习这种静态数组+idx的用法很好用速度快。
//转换好的数字按m进制数的标准样式输出
for (int i = output.size() - 1; i >= 0; i--) cout << int_to_char(output[i]);
return 0;
}