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

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

题目描述:

PAT-BASIC1048——数字加密

知识点:字符串

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

本题有一个坑点:

当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++解题报告:

PAT-BASIC1048——数字加密

 

相关文章: