1252进制转换

进制转换
Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem 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

Source
HDOJ
THINK:
根据m的取值范围进行分类,m>10的时候要另开一个数组,原因是有字符,这时候要注意把数字转换成字符,直接+‘0’;m<10的时候直接入栈就行了;另外这两种情况要注意n是负数的时候,要进行‘-’的输出;

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int a[500];
char b[200];//用来盛放m>10的时候的ABCDEF的
int main()
{
    int n,m,top,top2;
    while(~scanf("%d%d",&n,&m))
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        top=0;top2=0;
        int t;
        if(n==0)printf("0\n");
        else
        {
            if(n<0) {t=n;n=-n;}//注意负数的输出
            else t=n;
            if(m>10)//第一种情况
            {
                while(n!=0)
                {
                    int s;
                    s=n%m;
                    n=n/m;
                    //printf("%d ",s);
                    if(s==10)
                    {
                        b[++top2]='A';
                    }
                    else if(s==11)
                    {
                        b[++top2]='B';
                    }
                    else if(s==12)
                    {
                        b[++top2]='C';
                    }
                    else if(s==13)
                    {
                        b[++top2]='D';
                    }
                    else if(s==14)
                    {
                        b[++top2]='E';
                    }
                    else if(s==15)
                    {
                        b[++top2]='F';
                    }
                    else b[++top2]=s+'0';//这样可以直接由数字转换成字符
                }
                    if(t<0)
                    {
                        printf("-");
                    }
                    while(top2!=0)
                    {
                        printf("%c",b[top2--]);
                    }
                    printf("\n");
            }
            else
            {
                while(n!=0)
                {
                    int s=n%m;
                    n=n/m;
                    a[++top]=s;
                }
                if(t<0)
                    {
                        printf("-");
                    }
                    while(top!=0)
                    {
                        printf("%d",a[top--]);
                    }
                    printf("\n");
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/bhliuhan/article/details/81163418