EOJ 3037 十六进制加法

请编写程序实现两个十六进制整数的加法。

例如:十六进制整数 3762 和 05C3,3762+05C3 =3D25

十六进制整数 CB9 和 957,CB9+957=1610

Input

第 1 行:一个整数 T (1T10) 为问题数。

接下来 T 行,每行输入两个十六进制整数 n 和 m (n,m 为不超过 200 位的十六进制整数),A~F 全部为大写字母。 两个整数之间用一个空格分隔。

Output

对于每个问题,输出一行问题的编号(0 开始编号,格式:case #0: 等)。然后对应每个问题在一行中输出两个十六进制整数相加的结果,字母全部用大写字母。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 int init(char *a)
 4 {
 5     char c;
 6     int pos=1;
 7     while((c=getchar())!=' '&&c!='
')
 8         a[pos++]=c;
 9     a[pos]=0;
10     return pos-1;
11 }//返回值是为了确定两个数组的长度
12 int ctoi(char c)    {return (c>='0'&&c<='9')?c-'0':c-'A'+10;}
13 char itoc(int i)     {return i<=9?i+'0':i-10+'A';}
14 void add(char* to,char* from,int t,int f)
15 {
16     int carry;char plus='0';
17     for(;from[f]!=0;f--,t--)
18     {
19         carry=ctoi(to[t])+ctoi(from[f])+ctoi(plus); 将两位转化成整数后相加
20         to[t]=itoc(carry%16);
21         plus=itoc(carry/16);//进位
22     }
23     while(t>=0&&(carry=ctoi(to[t])+ctoi(plus))>0)//不停进位的情况
24     {
25         to[t]=itoc(carry%16);
26         plus=itoc(carry/16);
27         t--;
28     }
29     if(plus>'0')
30         to[0]=plus;//留下一位空格以放置最后的进位
31 }
32 void print(char *s)
33 {
34     char *p=s;
35     if(p[0]==0) p++;//遗留的空位可能没有被使用
36     printf("%s
",p);
37 }
38 int main()
39 {
40     int cas;scanf("%d",&cas);getchar();
41     for(int m=0;m<cas;m++)
42     {
43         char a[202],b[202];
44         int pa,pb;
45         a[0]=b[0]=0;//留下一位空格以放置最后的进位
46         pa=init(a);
47         pb=init(b);
48         printf("case #%d:
",m);
49         if(pa>=pb)//哪个长就把结果放置在哪个里
50         {
51             add(a,b,pa,pb);
52             print(a);
53         }
54         else
55         {
56             add(b,a,pb,pa);
57             print(b);
58         }
59     }
60     return 0;
61 }

类似于大整数,还是有固定的模板的。

原文地址:https://www.cnblogs.com/Jiiiin/p/8616927.html