PAT乙级1048 数字加密(Cpp)

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

输入格式:

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

输出格式:

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

输入样例:

1234567 368782971

输出样例:

3695Q8118

 

代码如下:

#include <cstdio>
#include <cstring>
#include <string>
using namespace std; 

char getStr(int temp) {
	char c;
	if (temp == 10) c = 'J';
	else if (temp == 11) c = 'Q';
	else if (temp == 12) c = 'K';
	else if (temp == 9) c = '9';
	else if (temp == 8) c = '8';
	else if (temp == 7) c = '7';
	else if (temp == 6) c = '6';
	else if (temp == 5) c = '5';
	else if (temp == 4) c = '4';
	else if (temp == 3) c = '3';
	else if (temp == 2) c = '2';
	else if (temp == 1) c = '1';
	else if (temp == 0) c = '0';
	return c;
} 

int main() {
	char strA[109], strB[109], re[109];
	scanf("%s %s", strA, strB);
	int lena = strlen(strA);
	int lenb = strlen(strB); 
	//int len = sizeof(strA) / sizeof(strA[0]);		此方法获取的数组长度为 109 
	int flag = 1, k;
	if (lena < lenb) k = lenb;
	else k = lena;
	int max = k;
	int a = lena - 1, b = lenb - 1;
	int temp;
	k -= 1;
	while(k >= 0) {
		if (flag) {
			temp = strB[b] + strA[a] - 96;
			temp = temp % 13;
			re[k] = getStr(temp);
			b--; 
			a--;
			flag = 0;
		}
		else {
			temp = strB[b] - strA[a];
			if (temp < 0) temp += 10;
			re[k] = getStr(temp);
			b--;
			a--;
			flag = 1;
		}
		if (a < 0) {
			a = 0;
			strA[0] = '0';
		}
		if (b < 0) {
			b = 0;
			strB[0] = '0';
		}
		k--;
	}
	for (int i = 0; i < max; i++) printf("%c", re[i]);
}

小坑:一开始因为题干理解有误导致测试点2、5未通过。题干理解为,若a较长则b补0,若b较长则a补0。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值