Problem Description
Many classmates said to me that A+B is must needs.
If you can’t AC this problem, you would invite me for night meal. ^_^ |
Input
Input may contain multiple test cases. Each case contains A and B in one line.
A, B are hexadecimal number. Input terminates by EOF. |
Output
Output A+B in decimal number in one line.
|
Sample Input
1 9
A B
a b
|
Sample Output
10 21 21 |
Author
威士忌
|
Source
HZIEE 2007 Programming Contest
|
Recommend
lcy
|
最近刷ACM的水題時又碰到了A+B的題,其實是很簡單的一道題,結果我卻沒有審清題意!【雖然題目中的英文錯誤很多...
我將題目中的“A, B are hexadecimal numbers”僅僅理解成Sample Input中標紅的A和B,於是就有了下面的錯誤答案:
#include <iostream> //isalpha()
#include <stdlib.h> //atof()
#include <stdio.h>
#include <string.h> //strlen()
using namespace std;
void changeAlphaToDecimal(char a, double &b) {
switch(a) {//寫switch語句檔次有點low了,但是我當時就是這麼寫的,就懶得改了..
case 'A' :
case 'a' : b = 10; break;
case 'B' :
case 'b' : b = 11; break;
case 'C' :
case 'c' : b = 12; break;
case 'D' :
case 'd' : b = 13; break;
case 'E' :
case 'e' : b = 14; break;
case 'F' :
case 'f' : b = 15; break;
}
}
int main()
{
char a[100] = {'\0'}, b[100] = {'\0'};
while (scanf("%s %s",a,b) != EOF) {
double _a, _b;
if (strlen(a) == 1) {
char a_ = a[0];
if (!isalpha(a_)) {
_a = atof(a);
}
/*!
if (isdigit(a)) { //因爲當時還考慮到了輸入浮點數相加的情況,所以沒有使用isdigit()
_a = a-48;
}
*/
else {
changeAlphaToDecimal(a_, _a);
}
} else {
_a = atof(a);
}
if (strlen(b) == 1) {
char b_ = b[0];
if (!isalpha(b_)) {
_b = atof(b);
} else {
changeAlphaToDecimal(b_, _b);
}
} else {
_b = atof(b);
}
cout <<_a + _b<<endl;
}
return 0;
}
寫出這個答案之後,當時心中還暗暗得意,覺得自己還考慮了兩個浮點數相加的情況,肯定能Accepted...
但結果就是Wrong Answer!
百思不得其解之後,我在網上找到了這個可以AC的答案:
#include <iostream>
int main()
{
int a,b;
while(cin>>hex>>a>>hex>>b)
cout<<a+b<<endl;
return 0;
}
突然恍然大悟,原來題目中的A和B代表的就是所有輸入的A和B必須都是16進制的數!根本不需要考慮浮點數相加的情況!
因爲這本身就是一個A+B問題!A和B就代表了問題本身!
而我之前的答案是無法解決,諸如:AA + BB 這樣的十六進制數的相加問題的!
切記,以後一定要審清題目再動手!減少眼高手低的情況!