PAT (Basic Level) 1048 数字加密

本题要求实现一种数字加密方法。首先固定一个加密用正整数 A,对任一正整数 B,将其每 1 位数字与 A 的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对 13 取余——这里用 J 代表 10、Q 代表 11、K 代表 12;对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。

输入格式:

输入在一行中依次给出 A 和 B,均为不超过 100 位的正整数,其间以空格分隔。

输出格式:

在一行中输出加密后的结果。

输入样例:

1234567 368782971

输出样例:

3695Q8118

分析:

1.个位是从字符串最后一位开始得到。

2.不管哪个字符短,都要补齐(太坑),将字符串反转,很容易在最后补‘0’。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
	string str1, str2;
	int a[100];
	cin >> str1 >> str2;
	reverse(str1.begin(), str1.end());
	reverse(str2.begin(), str2.end());
	if (str1.size() > str2.size())
		str2.append(str1.size() - str2.size(), '0');
	else if(str1.size() < str2.size())
		str1.append(str2.size() - str1.size(), '0');
	int A, B;
	for (int i = 0; i < str1.length(); i++)
	{
		A = str1[i] - '0';
		B = str2[i] - '0';
		if (i % 2 == 0)//奇数
		{
			a[i] = (A + B) % 13;
		}
		else//偶数
		{
			a[i] = (B - A + 10) % 10;
		}
	}
	for (int i = str1.length() - 1; i >= 0; i--)
	{
		if (a[i] == 10)
			cout << "J";
		else if (a[i] == 11)
			cout << "Q";
		else if (a[i] == 12)
			cout << "K";
		else
			cout << a[i];
	}
}

猜你喜欢

转载自blog.csdn.net/Fcity_sh/article/details/81454285