原题
解析
这道题原本是不难的,但就是实在是题目描述的不好。
正确做法是,当给出的b比a短的时候,需要在b前面补0;而在加密结果的开头有0时则无需处理。
代码
#include <iostream>
#include <stack>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
stack<char> s;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
unsigned long len=min(a.length(),b.length());
if (b.length() < a.length()) {
unsigned long len_0 = a.length() - b.length();
for (int i = 0;i < len_0;i++) b.append("0");
len = b.length();
}
int cnt = 1;
for (int i = 0;i < len; ++i) {
if (cnt % 2 == 1) {
int t;
t = ((a[i] - '0') + (b[i] - '0')) % 13;
//cout << t << endl;
char c;
if (t == 10) c = 'J';
else if (t == 11) c = 'Q';
else if (t == 12) c = 'K';
else c = '0' + t;
s.push(c);
}
else {
int t = 0;
t = (b[i] - '0') - (a[i] - '0');
if (t < 0) t += 10;
//cout << t << endl;
s.push('0' + t);
}
cnt++;
}
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
if (a.length() > b.length()) {
for (int i = 0;i < a.length() - len;i++) cout << a[i];
}
else {
for (int i = 0;i < b.length() - len;i++) cout << b[i];
}
//while (s.top() == '0') s.pop();
while (s.size() > 0) {
cout << s.top();
s.pop();
}
cout << endl;
}
这个坑搞得我心态炸了,自己研究了好久也没研究出来。还以为是结果中0的处理,但后来发现不是,最后上网查了才发现。所以代码改的有点丑,见谅。