Title Description
Given a decimal number M, and the need to convert the binary number N. M decimal number into binary number N
input Description:
input line, M (32-bit integer), N (2 ≤ N ≤ 16), separated by a space.
Output Description: The
number of converted output for each test case, each output per line. If rule number N is greater than 9, then the corresponding hexadecimal reference (for example, represented by 10 A, etc.)
Example
Input 72
Output 111
#include <iostream>
#include <stack>
using namespace std;
int main(){
long int num;
int n, i, size;
int flag = 0;
stack<int> src;
char arr[6] = { 'A', 'B', 'C', 'D', 'E', 'F' };
cin >> num;
cin >> n;
if (num < 0){//如果是负数,就转换为正数
num = 0 - num;
flag = 1;
}
while (num){
src.push(num % n);
num = num / n;
}
size = src.size();
if (flag){
cout << '-';
}
for (i = 0; i < size; i++){
if (src.top() > 9){
cout << arr[src.top() % 10];
src.pop();
}
else{
cout << src.top();
src.pop();
}
}
system("pause");
return 0;
}
Outline of Solution:
Decimal N-ary conversion, is in addition modulo N, then reverse the output, until the end of the operation is 0, the process according to this operation, a stack can be defined to store the remainder at the end of calculation, pop side edge printing to be available. Note converted to hexadecimal when ABC ... appears.