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
通过阅读该题可知,该题是进制转换的基础题,输入两个16进制的数,计算出两个数的和,并输出16进制的结果。一开始看到这道题,认为比较难处理的是16进制前的正负号,后来看到c++的输入输出流,发现正负号其实没什么影响。
//利用 cin >> hex >> a >> b 可以输入两个16进制的数,并且前面可以有 + - 号
long long a,b;
cin >> hex >> a >> b;
然后可以利用 cout << hex << a << b 可以输出两个16进制的数,但是并没有正负号,而且当数值为负时,输出的16进制为补码,与OUTPUT不符。
所以我们可以利用简单的判断,将 负号 提前输出,在将 负的数值 转成 正的 输出即可。
if(num1+num2<0){
cout << "-";
cout << setiosflags(ios::uppercase) << hex << -(num1+num2) << endl;
}
else cout << setiosflags(ios::uppercase) << hex << (num1+num2) << endl;
//其中 setiosflags(ios::uppercase) 是为了使输出的16进制是字符是大写。
#include
#include
using namespace std;
int main(){
long long num1, num2;
while(cin >> hex >> num1 >> num2){
if(num1+num2<0){
cout << "-";
cout << setiosflags(ios::uppercase) << hex << -(num1+num2) << endl;
}
else cout << setiosflags(ios::uppercase) << hex << (num1+num2) << endl;
}
return 0;
}