A + B Again
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 21410 Accepted Submission(s): 9250
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 !
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.
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
Author
linle
Source
Recommend
linle | We have carefully selected several similar problems for you: 2060 2058 2059 2061 1002
#include<stdio.h>
#include<String.h>
int toHex(__int64 a,char s[]){
int index = 0,l;
memset(s,0,sizeof(s));
if(a<0){
a = -a;
index = 1;
s[0] = '-';
}
do{
l = a%16;
if(l>9){
s[index++] = 'A' + l -10;
}else{
s[index++] = '0' + l ;
}
a = a/16;
}while(a!=0);
return index; //此处如不返回index表示数组元素个数的话 数组长度会不对 我也不知道为什么....
}
__int64 toDec(char s[]){
char sy[2] = {0}; //符号位
int index = 0,len = strlen(s);
__int64 c = 1,sum = 0; //C不断乘16 sum结果
if(s[0] == '-'||s[0] == '+'){
sy[0] = s[0];index = 1;
}
for(int i = len-1;i >=index;i--){
if(s[i]>='A'&&s[i]<='F'){
sum += ((int)(s[i] - 55))*c; //大写英文字符
}else{
sum += (s[i]-48)*c; //数字字符
}
c = c*16;
}
//printf("%I64d\n",c);
//printf("%I64d\n",sum);
if(sy[0]=='-'){
return -sum;
}else{
return sum;
}
}
int main(){
char a[20],b[20],c[20];
__int64 add,len;
while(scanf("%s%s",a,b)!=EOF){
add = toDec(a)+toDec(b);
len = toHex(add,c);
if(c[0]=='-'){
printf("-");
for(int i = len -1 ;i >= 1 ;i--){
printf("%c",c[i]);
}
}else{
for(int i = len -1 ;i >= 0 ;i--){
printf("%c",c[i]);
}
}
printf("\n");
}
return 0;
}