hdoj2057A + B Again(字符串)

来源:互联网 发布:摩擦纳米发电机 知乎 编辑:程序博客网 时间:2024/06/05 02:53
Problem Description
There must be many A + B problems in our HDOJ , now a new one is coming.
Give you two hexadecimal integers , your task is to calculate the sum of them,and print it in hexadecimal too.
Easy ? AC it !


Input
The input contains several test cases, please process to the end of the file.
Each case consists of two hexadecimal integers A and B in a line seperated by a blank.
The length of A and B is less than 15.


Output
For each test case,print the sum of A and B in hexadecimal in one line.



Sample Input
+A -A
+1A 12
1A -9
-1A -12
1A -AA


Sample Output
0
2C
11
-2C

-90

代码:

#include<stdio.h>#include<iostream>#include<string.h>#include<algorithm>using namespace std;int main(){char a[101],b[101],c[101],d[101],zong[101];while(~scanf("%s %s",a,b)){__int64 sum,sum1=0,sum2=0;int n1=strlen(a),n2=strlen(b);for(int i=0;i<n1;i++){if(a[i]=='+'||a[i]=='-')continue;if(a[i]=='A')a[i]=10;else if(a[i]=='B')a[i]=11;else if(a[i]=='C')a[i]=12;else if (a[i]=='D')a[i]=13;else if(a[i]=='E')a[i]=14;else if(a[i]=='F')a[i]=15;if(a[0]!='-'){if(a[i]>=48)a[i]-='0';sum1*=16;sum1+=a[i];}else {if(a[i]>=48)a[i]-='0';sum1*=16;sum1-=a[i];}}for(int i=0;i<n2;i++){if(b[i]=='+'||b[i]=='-')continue;if(b[i]=='A')b[i]=10;else if(b[i]=='B')b[i]=11;else if(b[i]=='C')b[i]=12;else if(b[i]=='D')b[i]=13;else if(b[i]=='E')b[i]=14;else if(b[i]=='F')b[i]=15;if(b[0]!='-'){if(b[i]>=48)b[i]-='0';sum2*=16;sum2+=b[i];}else {if(b[i]>=48)b[i]-='0';sum2*=16;sum2-=b[i];}}sum=sum1+sum2;if(sum<0){printf("-");sum=-sum;}if(sum==0)printf("0\n");else{int k=0;while(sum>0){if(sum%16==10){zong[k++]='A';sum/=16;}else if(sum%16==11){zong[k++]='B';sum/=16;}else if(sum%16==12){zong[k++]='C';sum/=16;}else if(sum%16==13){zong[k++]='D';sum/=16;}else if(sum%16==14){zong[k++]='E';sum/=16;}else if(sum%16==15){zong[k++]='F';sum/=16;}else{zong[k++]=sum%16+'0';sum/=16;}}for(int i=k-1;i>=0;i--)printf("%c",zong[i]);printf("\n");}}return 0;}
思路:这道字符串wa了好多次,最开始做的时候天真的直接以为是输出a+b,然后wa,后来以为是定义型小了,用__int64 还是wa,最后才发现是用字符组做。这道题是16进制的数,可以先把他转化为十进制加减后在转化回十六进制输出。注意判断正负号,如果是负号可以先保存下然后用正值计算。最后结果如果是负数可以先直接输出-号然后在输出转化后的数。


0 0
原创粉丝点击