Problem Description
输入一个十进制数N,将它转换成R进制数输出。
Input
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R != 10)。
Output
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
Example Input
7 2
23 12
-4 3
Example Output
111
1B
-11
题意:
将十进制转换成R进制,余数在0-9范围内用数字0-9,余数大于等于10,用字母A,B,C,D……..十六进制数代替。
分析:
可以用字符表示,0-9可以用字符‘0’+余数的方法转换成字符数字,>=10的余数用 余数-10+‘A’的方式转换成字符。
注意n 为0和为负数的情况。
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int main()
{
int n, r;
char s[200];
while(scanf("%d %d", &n, &r)!=EOF)
{
if(n==0)
{
printf("0\n");
continue;
}
if(n < 0)
{
printf("-");
n = -n;
}
int m;
int cnt = 0;
while(n > 0)
{
m = n%r;
if(m<=9)
s[cnt++] = '0'+m;
else
s[cnt++] = m-10+'A';
n = n/r;
}
for(int j = cnt-1;j >=0;j--)
printf("%c",s[j]);
printf("\n");
}
return 0;
}