Topic: Conversion System
Title description
Convert the number X in M system to the output in N system.
Input
The first line, an integer T, represents the number of test data sets.
Next to line T, enter the 32-bit binary number
Output
Output the number represented by the N system of X.
Test sample
input
10 2
11
Output
1011
Note : Note that if there is a letter when inputting, the letter is uppercase, if there is a letter when outputting, the letter is lowercase.
When I first looked at the question, I was ashamed. Where have I heard hexadecimal in the past? It scared me, but when you understand that hexadecimal is the so-called hexadecimal and then use GHI ... Z, it suddenly becomes cheerful ง • ̀_ • ́) ง |
---|
Ideas:
1. Process the input process first, assign a value to the corresponding value
2, convert the M-ary X to decimal
3, convert the decimal to N-ary
4, output processing
The procedure is as follows:
#include <iostream>
#include <stack>
#include <math.h>
using namespace std;
/**
* 一个十进制整数转换为N进制之间的任意进制数输出
* @param ary :要转换的进制
* @param num :要转换的数
*/
void Dec_To_All(int ary, long long int num) {
int temp = 0;
stack<char> number_stack;
if (ary <= 36 || ary > 1) { //不满足条件则退出
if (ary > 1 && ary < 10) { //2-9进制
while (1) {
temp = num % ary; //进制转换
number_stack.push(temp + '0'); //压栈,这里需要加上 '0' 因为栈定义为char类型
num = num / ary; //计算剩余数
if (num == 0)
break;
}
} else if (ary == 10) //10进制
cout << num << endl;
else if (ary > 10 && ary < 36) { //11-36进制
while (1) {
temp = num % ary ; //进制转换
if(temp > 9)
temp = temp - 10 + 'a'; //设置为a 开始,输出为a
else
temp = temp + '0'; //这里转换为字符
number_stack.push(temp); //压栈
num = num / ary; //计算剩余数
if (num == 0)
break;
}
}
while (!number_stack.empty()) {
cout << number_stack.top(); //得到栈顶元素
number_stack.pop(); //出栈
}
}
}
/**
* 任意进制转换为10进制
* @param ary 目前的进制数
* @param num 要转换的数
* @return
*/
long long int All_to_Dec(int ary, string num) {
long long int result = 0;
long long int temp = 0, i = 0;
if (ary > 36 || ary < 0)
return 0;
for (int j = 0; j < num.size(); ++j) {
if (num[j] >= '0' && num[j] <= '9') {
temp = (num[j] - '0') * pow(ary, num.size() - 1 - j); //计算这个字母对应的数字
} else if (num[j] >= 'A' && num[j] <= 'Z') {
temp = (num[j] - 'A' + 10) * pow(ary, num.size() - 1 - j); //计算这个字母对应的数字
}
result += temp;
}
return result;
}
/**
* 将M进制的数X转换为N进制的数输出。(2<=M,N<=36)
*/
int main() {
int M = 0, N = 0;
string X = ""; //要转换的数
cin >> M >> N; //获取初始进制数M和目标进制数N
cin >> X; //需要转换的数
long long int dec_num = All_to_Dec(M, X); //M进制转换为十进制数,这里需要用long long才能存下
Dec_To_All(N, dec_num); //十进制转换为N进制
return 0;
}
note:
- The stack is used for storage, and the pushed elements must be converted to the type defined by the stack
- Remember
‘A’ = 65
‘a’=97
'0' = 48
the values corresponding to these commonly used ASCII codes
End