代码
#include <iostream>
using namespace std;
int main() {
string s1, s2;
cin>>s1>>s2;
//put the length same
while(s1.length()<s2.length()) {
s1 = "0" + s1;
}
while(s2.length()<s1.length()) {
s2 = "0" + s2;
}
string ans;
int pos = 1;
string reminder = "0123456789JQK";
for(int i=s1.length()-1; i>=0; i--) {
if(pos%2) {
ans += reminder.at((s1.at(i)-'0'+s2.at(i)-'0')%13);
} else {
// >=0 , not > 0, otherwise there will be 3 wrong answer cases!
ans += s2.at(i)-s1.at(i)>=0?s2.at(i)-s1.at(i)+'0':s2.at(i)-s1.at(i)+'0'+10;
}
pos++;
}
for(int i=ans.length()-1; i>=0; i--) {
cout<<ans.at(i);
}
cout<<endl;
return 0;
}
注解
1、细节决定成败,读题很重要!!一开始一直是15分,有3个案例错误,找了很久都没找到。后来发现原题是:对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。
负数!所以应该是s2-s1>=0,而我这里一开始写成了s2-s1>0。于是s2-s1==0的情况就会多加了10,难怪会有三个案例错误!
// >=0 , not > 0, otherwise there will be 3 wrong answer cases!
ans += s2.at(i)-s1.at(i)>=0?s2.at(i)-s1.at(i)+'0':s2.at(i)-s1.at(i)+'0'+10;
2、要考虑s1与s2长度不一致的情况,解决办法是开头补0,直到二者长度一致。