(HDOJ2031)进制转换

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
 
 1 #include <stdio.h>
 2 #include <math.h>
 3 #include <string.h>
 4 #include <ctype.h>
 5     
 6     
 7 int a[1000];
 8   
 9 int absplus(int n)
10 {  return n>0?n:(-n); }
11   
12 void print(int a[],int n)
13 {
14   int i;
15   for(i=n; i>=0; i--)
16   {
17      if(a[i]<10)  
18      {
19        printf("%d",a[i]);
20      }
21      else
22      {
23        switch(a[i]%10)
24        {
25          case 0:printf("A");break;
26          case 1:printf("B");break;
27          case 2:printf("C");break;
28          case 3:printf("D");break;
29          case 4:printf("E");break;
30          case 5:printf("F");break;
31        }
32       }
33    }
34 }
35     
36 void convert(int n, int R)
37 {
38    int i=0,p,j;
39    int t;
40    t=n;
41    n=absplus(n);
42    a[0]=n%R;
43    p=n/R;
44    while(p>=R)
45    {
46       a[++i]=p%R;
47       p=p/R;
48    }
49    a[++i]=p;
50    if(t>0)
51    {
52      print(a,i);
53    }
54    else
55    {
56       printf("-");
57       print(a,i);
58    }
59    printf("\n");
60        
61 }
62     
63 int main()
64 {
65   int N,R;
66   while(scanf("%d%d",&N,&R)!=EOF)
67   {
68      if((N==1) || (N==0))
69       printf("%d\n",N);
70      else
71       convert(N,R);
72   }
73   return 0;
74 }
原文地址:https://www.cnblogs.com/cpoint/p/3011360.html