本题要求实现一种数字加密方法。首先固定一个加密用正整数 A,对任一正整数 B,将其每 1 位数字与 A 的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对 13 取余——这里用 J 代表 10、Q 代表 11、K 代表 12;对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。
输入格式:
输入在一行中依次给出 A 和 B,均为不超过 100 位的正整数,其间以空格分隔。
输出格式:
在一行中输出加密后的结果。
输入样例:
1234567 368782971
输出样例:
3695Q8118
解题思路:
- 首先,使用 r e v e r s e ( ) reverse() reverse() 函数对字符数组 a a a、 b b b倒置, m a x ( ) max() max() 函数取字符数组长度最大值 l e n len len ,定义字典数组 d i c dic dic 为 从 0~K
- 遍历字符数组, n u m 1 num1 num1 代表 a [ i ] a[i] a[i] 的数字值, n u m 2 num2 num2 代表 b [ i ] b[i] b[i] 的数字值,奇数位则将 c [ i ] c[i] c[i] 为 ( n u m 1 + n u m 2 ) (num1 + num2) (num1+num2) % 13 13 13 的字典对应值;偶数位则 n u m 1 + n u m 2 num1 + num2 num1+num2,如果小于0就加10的字典对应值,倒序输出字符数组 c c c
答案代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
using namespace std;
char dic[14] = {"0123456789JQK"};
int main() {
string a, b, c;
cin >> a >> b;
int lena = a.length(), lenb = b.length();
reverse(a.begin(), a.end()); // 字符串逆序
reverse(b.begin(), b.end());
int fill = abs(lena - lenb);
lena > lenb ? b.append( fill , '0') : a.append( fill, '0'); // 补零
int len = max(lena, lenb);
for (int i = 0; i < len; i++) {
int num1 = i < lena ? a[i] - '0' : 0;
int num2 = i < lenb ? b[i] - '0' : 0;
if (i % 2 == 0) {
c.push_back(dic[(num1 + num2) % 13]);
} else {
int tmp = num2 - num1;
if (tmp < 0) tmp += 10;
c.push_back(tmp + '0');
}
}
reverse(c.begin(),c.end());
cout << c << endl;
return 0;
}