PAT乙级刷题之路1048 数字加密 (20分)

1048 数字加密 (20分)

本题要求实现一种数字加密方法。首先固定一个加密用正整数 A,对任一正整数 B,将其每 1 位数字与 A 的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对 13 取余——这里用 J 代表 10、Q 代表 11、K 代表 12;对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。
输入格式:
输入在一行中依次给出 A 和 B,均为不超过 100 位的正整数,其间以空格分隔。
输出格式:
在一行中输出加密后的结果。
输入样例:
1234567 368782971
输出样例:
3695Q8118

很巧的:(B[i]-A[i]+10)%10来避免判断B[i]-A[i]的正负

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
	string A,B,result;
	cin>>A>>B;
	//因为这里令个位为第 1 位。
	reverse(A.begin(),A.end());
	reverse(B.begin(),B.end());
	//用0把长度不相同时的A和B补齐
	if(A.length() <B.length())
		A+=string(B.length()-A.length(),'0');
	else if(A.length() > B.length())
		B+=string(A.length()-B.length(),'0');
	int len = B.length();
	for(int i=0;i !=len;i++){
		if(i%2 == 0){//奇数位
			int temp = (A[i]+B[i]-'0'-'0')%13;
			if(temp ==10) result+='J';
			else if(temp == 11)  result+='Q';
			else if(temp == 12) result+='K';	
			else result+=temp+'0';
		}else{//偶数位
            result+=(B[i]-A[i]+10)%10+'0';
        }			
	}
	reverse(result.begin(),result.end());
	cout<<result;
}

发布了73 篇原创文章 · 获赞 0 · 访问量 541

猜你喜欢

转载自blog.csdn.net/derbi123123/article/details/103791053
今日推荐