hdu 2057

A + B Again

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


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 <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;


int hex2dec(char s[]){
    int res=0;
    int flag=0;
for(int i=0;i<strlen(s);i++){
    if(s[i]=='-')
       flag=1;
    if(s[i]>='0'&&s[i]<='9')
        {
            int a=s[i]-48;


            res+=a*pow(16,strlen(s)-i-1);
        }
        if(s[i]>='A'&&s[i]<='Z'){
            int c=s[i]-55;
            res+=c*pow(16,strlen(s)-i-1);
        }


    }
    if(flag==1)
        return -res;
    else
        return res;
}
char f[100];
void dec2hex(int x){


    int flag=0;
    char f1[100];
    if(x<0){
        flag=1;
        x=-x;
    }
    int i=0,d=0;char c;
    if(x==0)
        f[d++]=x+48;
    if(flag==1){
        f[d++]='-';
    }
    while(x!=0){
    int r=x%16;
     x/=16;
     if(r>=0&&r<=9){
        c=r+48;
     }
     if(r>=10&&r<16)
        c=r+55;
    f1[i++]=c;
    }
    for(int j=i-1;j>=0;j--){
        f[d]=f1[j];
        d++;
    }
}
int main()
{
    char a[100],b[100];
    while(~scanf("%s%s",a,b))
{
    int s=hex2dec(a)+hex2dec(b);
    dec2hex(s);
    for(int i=0;i<strlen(f);i++)
    cout<<f[i];
    cout<<endl;
}
    return 0;
}
上面代码是我写的十进制十六进制代码互转。
像c的话有各种进制控制输出,不必这么麻烦。代码如下:
#include<cstdio>
#include<cstring>
#include <iostream>
using namespace std;

int main()
{
    long long i,j,n;
    while(~scanf("%llX%llX",&i,&j))//十六进制输入
    {
       n=i+j;
       if(n>=0)
       printf("%llX\n",n);//十六进制输出
       else
        printf("-%llX\n",-n);//十六进制负数输出,由于十六进制是无符号型输出的所以前要加负号
    }

return 0;
}














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值