B1048 数字加密 (20 分) 【避免入坑

看起来挺普通的一道题为什么通过率不高呢? 刚开始一直是16分(满分20),百度了一番……

如果A 和 B的长度相等,按照题意处理即可。如果A的长度小于B的长度,按照样例我们可以在A的前面补上适当的零。这背后的逻辑是,如果A相应的位上是零,加密操作不会改变B对应位上的数字。 那么,疑问来了,如果A的长度大于B呢? 答案竟然是在B的前面也补上足够的零

按我刚开始的思路,直接将较长的那个数组剩余的数字直接输出,不给补0,在A的长度大于B的长度时,B-A的时候就会出现错误奥~~~~ 也是扣分点

然后这个题还有个小注意点就是字符与数字的转换:

  • 字符转数字 -‘0’
  • 数字转字符 +‘0’

满分代码

#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

char a[110], b[110], res[110]={
    
    '0'};

void reverse(char s[], int len){
    
    
	int temp;
	for(int i = 0; i < len/2; i++){
    
    
		temp = s[i];
		s[i] = s[len-i-1];
		s[len-i-1] = temp;	
	}
}

int main(int argc, char** argv) {
    
    
	
	scanf("%s %s", a, b);
	
	int len_a = strlen(a);
	int len_b = strlen(b);
	
	reverse(a, len_a);
	reverse(b, len_b);
	
	int len = max(len_a, len_b);
	
	for(int i = 0; i < len; i++){
    
    
		int numa = i < len_a ? a[i] - '0' : 0;
		int numb = i < len_b ? b[i] - '0' : 0;
		int temp = 0;
		if((i+1)%2 == 1){
    
    
			temp = (numa + numb) % 13;
			if(temp == 10) res[i] = 'J';
			else if (temp == 11) res[i] = 'Q';
			else if (temp == 12) res[i] = 'K'; 
			else res[i] = temp + '0';
		} else {
    
    
			temp = numb - numa;
			if(temp < 0){
    
    
				temp += 10;
			}
			res[i] = temp+'0';
		}
	}
	int len_res = strlen(res);
	reverse(res, len_res);
	puts(res);
	 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/alovelypeach/article/details/114267981