HDU2057

来源:互联网 发布:什么是数据库的安全性 编辑:程序博客网 时间:2024/06/16 17:58

A + B Again

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 20734    Accepted Submission(s): 8940


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 121A -9-1A -121A -AA
 

Sample Output
02C11-2C-90
 


遇到的问题和思路:

       水题。虽然一次AC了,不过在过程中出现了好多错误。因为个人的懒惰加上前后步骤相似,所以就复制粘贴了,然而付出的代价是惨痛的,浪费了很多时间在调试上面,以后应当慢慢打出来,总比复制粘贴以后调试所来的要快。


给出代码:


#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#define inf 1e-12


using namespace std;


long long sum1,sum2;
char a[16],b[16],c[19];


int main(){
while(scanf("%s %s",&a,&b)!=EOF){
sum1 = sum2 = 0;
getchar();
memset(c,0,sizeof(c));
//转换成十进制 
for(int i = 0;i < strlen(a);i++){
if(a[i]=='-'||a[i] == '+')continue;
else if(a[i] >= 'A'&&a[i] <= 'F')sum1 = sum1 * 16 + a[i]-'A'+10;
else sum1 = sum1 * 16 + a[i]-'0';
}
if(a[0] == '-')sum1*=-1;
for(int i = 0;i < strlen(b);i++){
if(b[i]=='-'||b[i] == '+')continue;
else if(b[i] >= 'A'&&b[i] <= 'F')sum2 = sum2 * 16 + b[i]-'A'+10;
else sum2 = sum2 * 16 + b[i]-'0';
}
if(b[0] == '-')sum2*=-1;
long long summ = sum1 + sum2;//求和 
//printf("%I64d %I64D %I64D\n",sum1,sum2,summ);
int count1 = 0;
//转换回十六进制 
if(summ < 0){
summ*=-1;
int i = 0;
while(summ){
if(summ % 16 >= 10)c[i] = summ % 16 + 'A' - 10;
else c[i] = summ % 16 + '0';
summ/=16;
i++;
}
c[i] = '-';
c[++i] = '\0';
}
else if(summ > 0){
int i = 0;
while(summ){
if(summ % 16 >= 10)c[i] = summ % 16 + 'A' - 10;
else c[i] = summ % 16 + '0';
summ/=16;
i++;
}
c[i] = '\0';
}
else {
c[0] = '0';
c[1] = '\0';
}
for(int i = strlen(c)-1;i >= 0;i--)printf("%c",c[i]);
printf("\n");
}
return 0;
}



0 0
原创粉丝点击