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.
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 ;
}