HDU2031 进制转换

Time Limit: 2000/1000 MS (Java/Others)

Memory Limit: 65536/32768 K (Java/Others)
[显示标签]
Description
输入一个十进制数N,将它转换成R进制数输出。
Input
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。
Output
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
Sample Input

7 2
23 12
-4 3

Sample Output

111
1B
-11

Hint
lcy
Source
   C语言程序设计练习(五)  
Related problem
2034 2032 2028 2030 2043

进制转换的计算,除进制数取余数。

我们可以在测试用例中看到,出现了负数,所以还要考虑符号问题。在下的方法是将符号存储起来,待到输出时再控制。

代码如下:

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int n,r;
    while(cin>>n>>r)
    {
        int t=n;
        n=fabs(n);
        if(n==0)
        {
            cout<<'0'<<endl;
            break;
        }
        int count=0;
        int a[32]={0};
        for(int i=0;n!=0;i++,count++)
        {
            a[i]=n%r;
            n/=r;
        }
        if (t<0)
            cout<<'-';
        for(int i=count-1;i>=0;i--)
        {
            if(a[i]<=9)
                cout<<a[i];
            else if(a[i]==10)
            cout<<'A';
        else if(a[i]==11)
            cout<<'B';
        else if(a[i]==12)
            cout<<'C';
        else if(a[i]==13)
            cout<<'D';
        else if(a[i]==14)
            cout<<'E';
        else
            cout<<'F';
        }
        cout<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41627235/article/details/82848133