题解 | #进制转换2#
进制转换2
http://www.nowcoder.com/practice/ae4b3c4a968745618d65b866002bbd32
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
int CharToInt(char c){
if(c >= '0' && c <= '9'){
return c - '0'; //数字型字符转数字
}else{
return c - 'A' + 10; //字符型字符转数字
}
}
char IntToChar(int target){
if(target < 10){
return target + '0';
}else{
return target + 'a' - 10;
}
}
long long ConvertM2T(string str,int current){ //current为当前需转换的目标的当前进制
long long number = 0;
for(int i = 0; i < str.size(); ++i){
number *= current;
number += CharToInt(str[i]);
}
return number;
}
void ConvertT2N(long long number,int target) { //target为目标进制
stack<char> myStack;
if(number == 0){
myStack.push('0');
}
while(number != 0) {
myStack.push(IntToChar(number % target));
number /= target;
}
while(!myStack.empty()) {
printf("%c",myStack.top());
myStack.pop();
}
printf("\n");
}
int main() {
int m,n;
while(scanf("%d%d",&m,&n) != EOF){
string str;
cin >> str;
long long number = ConvertM2T(str,m); //先转换成十进制
ConvertT2N(number,n); //再将十进制转n进制
}
return 0;
}