本题要求实现一种数字加密方法。首先固定一个加密用正整数 A,对任一正整数 B,将其每 1 位数字与 A 的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对 13 取余——这里用 J 代表 10、Q 代表 11、K 代表 12;对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。
输入格式:
输入在一行中依次给出 A 和 B,均为不超过 100 位的正整数,其间以空格分隔。
输出格式:
在一行中输出加密后的结果。
输入样例:
1234567 368782971
输出样例:
3695Q8118
思路
这题也是个水题,直接按照题目要求从低位开始对B串进行操作即可。
不过这里有个【坑点】:如果B串的长度小于A串的长度的话,需要在B串前面补0以达到和A串相同的长度。
代码
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<vector>
#include<string>
#include<string.h>
#include<iostream>
using namespace std;
int main()
{
string A, B, result;
cin>>A>>B;
while(B.length()<A.length()){
B.insert(0, "0");
}
reverse(A.begin(), A.end());
reverse(B.begin(), B.end());//低位在前
for(int i=0;i<B.length();i++){
if((i+1)%2==1&&i+1<=B.length()&&i+1<=A.length()){
if((A[i]-'0'+B[i]-'0')%13==10) result += 'J';
else if((A[i]-'0'+B[i]-'0')%13==11) result += 'Q';
else if((A[i]-'0'+B[i]-'0')%13==12) result += 'K';
else result += (A[i]-'0'+B[i]-'0')%13+'0';
}
else if((i+1)%2==0&&i+1<=B.length()&&i+1<=A.length()){
int b = B[i]-'0';
int a = A[i]-'0';
if(b-a<0) result += b-a+10+'0';
else result += b-a+'0';
}
else if(i+1>A.length()) result += B[i];
}
reverse(result.begin(), result.end());
cout<<result;
return 0;
}