PAT-BASIC1048——数字加密

本文详细解析了PAT-BASIC中一道关于字符串加密的题目,重点介绍了如何处理字符串长度不一致的情况,提供了C++代码实现及解题思路,时间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC

原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805276438282240

题目描述:

知识点:字符串

思路:根据题述规则加密即可

本题有一个坑点:

当B字符串的长度小于A字符串的长度时,加密时需要在B字符串前面补0直至和A字符串的长度相等。否则无法通过测试点2和测试点5。

当然我的做法不是在B字符前面补0,而是用0代替B中的字符去计算索引大于B字符串长度而小于等于A字符串长度那部分的加密数字。

时间复杂度是O(n),其中n为字符串A和字符串B中较大的长度值。空间复杂度也是O(n)。

C++代码:

#include<iostream>
#include<string>

using namespace std;

int main(){
	
	string a;
	string b;
	
	cin >> a >> b;
	
	int index = 1;
	string result = "";
	while(true){
		if(index > a.length() && index > b.length()){
			break;
		}else if(index > a.length() && index <= b.length()){
			result += b[b.length() - index];
			index++;
		}else if(index <= a.length() && index > b.length()){
			if(index % 2 == 1){
			int sum = (a[a.length() - index] - '0') % 13;
			if(sum == 10){
				result += 'J';
			}else if(sum == 11){
				result += 'Q';
			}else if(sum == 12){
				result += 'K';
			}else{
				result += (sum + '0');
			}
			index++;
		}else if(index % 2 == 0){
			int diff = -(a[a.length() - index] - '0');
			if(diff < 0){
				diff += 10;
			}
			result += (diff + '0');
			index++;
		}
		}else if(index % 2 == 1){
			int sum = ((a[a.length() - index] - '0') + (b[b.length() - index] - '0')) % 13;
			if(sum == 10){
				result += 'J';
			}else if(sum == 11){
				result += 'Q';
			}else if(sum == 12){
				result += 'K';
			}else{
				result += (sum + '0');
			}
			index++;
		}else if(index % 2 == 0){
			int diff = (b[b.length() - index] - '0') - (a[a.length() - index] - '0');
			if(diff < 0){
				diff += 10;
			}
			result += (diff + '0');
			index++;
		}
	}
	
	for(int i = result.length() - 1; i >= 0; i--){
		cout << result[i];
	}


	return 0;
}

C++解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值