【HDU】1720 A+B Coming
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1720
题目:
Problem Description
Many classmates said to me that A+B is must needs.
If you can’t AC this problem, you would invite me for night meal. ^_^
Input
Input may contain multiple test cases. Each case contains A and B in one line.
A, B are hexadecimal number.
Input terminates by EOF.Output
Output A+B in decimal number in one line.
Sample Input
1 9
A B
a b
Sample Output
10
21
21
代码:
刚开始做这道题,没有反应过来可直接如下转换。
最初做法,a、b均为正:
#include <stdio.h>
#include <ctype.h>
int main()
{
char a[1000], b[1000];
int n, m;
int i;
while (scanf("%s %s",a,b) != EOF)
{
n=0;m=0;
for (i=0; a[i]!='\0'; i++)
{
n *= 16;
if (isalpha(a[i]))n = n + (tolower(a[i])-'a') + 10;
else n = n + a[i] - '0';
}
for (i=0; b[i]!='\0'; i++)
{
m *= 16;
if (isalpha(b[i])) m = m + (tolower(b[i])-'a') + 10;
else m = m + b[i] - '0';
}
printf("%d\n",n+m);
}
return 0;
}
最初做法的改进:
后来发现我最初的做法,a、b必须均为正数,不然结果会出错(不过oj上未报错,可能其样例未使用含有负数的)。我又修正了一下,改进了代码,使得a、b不受限制。添加了判断a、b是否为正的变量isplusa和isplusb。代码如下:
#include <stdio.h>
#include <ctype.h>
int main()
{
char a[1000], b[1000];
int n, m;
int i,isplusa,isplusb;
while (scanf("%s %s",a,b) != EOF)
{
n=0;m=0;isplusa=1;isplusb=1;
for (i=0; a[i]!='\0'; i++)
{
if (a[i] == '-') {isplusa = 0;continue;}
n *= 16;
if (isalpha(a[i]))n = n + (tolower(a[i])-'a') + 10;
else n = n + a[i] - '0';
}
for (i=0; b[i]!='\0'; i++)
{
if (b[i] == '-') {isplusb = 0;continue;}
m *= 16;
if (isalpha(b[i])) m = m + (tolower(b[i])-'a') + 10;
else m = m + b[i] - '0';
}
if (!isplusa)n *= -1;
if (!isplusb)m *= -1;
printf("%d\n",n+m);
}
return 0;
}
简单写法:
后来发现没有那么复杂。
简单写法如下,注意输入十六进制数的表示情况。
#include <stdio.h>
int main()
{
int a,b;
while (scanf("%x%x",&a,&b) != EOF)
{
printf("%d\n",a+b);
}
return 0;
}