将十进制数M转换为N进制数
题目描述:给定一个十进制数M,以及需要转换的进制数N。将十进制数M转化为N进制数。
Exp:
输入:输入为一行,M(32位整数)、N(2 ≤ N ≤ 16),以空格隔开,如7,2。
输出:为每个测试实例输出转换后的数,每个输出占一行。如果N大于9,则对应的数字规则参考16进制(比如,10用A表示,等等),如111.
#include<iostream>
#include<string>
using namespace std;
string mton(int m, int n){
string s[16];
for (int i = 0; i < 16; i++){
if (i < 10){
s[i] = '0' + i;
}
else{
s[i] = 'A' - 10 + i;
}
}
string res;
while (m)
{
int temp = m % n;
res = s[temp] + res;
m = m / n;
}
return res;
}
int main(){
int m, n;
cin >> m >> n;
if (m<0){//考虑负数
cout << '-' + mton(-m, n) << endl;
}
else{
cout << mton(m, n) << endl;
}
return 0;
}