PAT1048数字加密(java实现)

题目描述:

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

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

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


解题思路:这道题主要技巧就是想到把短的那串数字用0去补充,这样输出的时候就能直接一个for循环搞定了。并且题目需要是不超过100位正整数,所以想到用字符串去接收。对于奇偶情况的不同处理,程序中用一个flag作为判断,就免去了考虑这个整数的位数原本是奇数还是偶数了。

易错点:这道题的输出的整数位数是和较长的那个保持一致,而不是我一开始以为的和后一个输入的保持一致。


程序:


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main{
public static void main(String[] args) throws Exception {
	BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	String ab = bf.readLine();
	String[] a = ab.split(" ");
	int alength = a[0].length();
	int blength = a[1].length();
	int max = alength >= blength?alength:blength;
	int[] result = new int[max];
	int d = (blength-alength>=0)?blength-alength:alength-blength;
	if (d!=0) {
		if (alength<blength) {
			for (int i = 0; i < d; i++) {
				a[0] = "0" + a[0];
			}
		}else {
			for (int i = 0; i < d; i++) {
				a[1] = "0" + a[1];
			}
		}
	}
	int flag = 1;
	for (int i = max-1 ; i >=0; i--) {
	int t1=Integer.parseInt(String.valueOf(a[0].charAt(i)));
	int t2=Integer.parseInt(String.valueOf(a[1].charAt(i)));
	flag = -flag;
		if (flag==-1) {
			result[i] = (t1+t2)%13;
		}
		int temp = t2-t1;
		if (flag==1&&temp>=0) {
			result[i] = temp;	
		}
		if(flag==1&&temp<0){
			result[i] = temp+10;	
		}
	}
		for (int i = 0; i <result.length; i++) {
			if (result[i]==10) {
				System.out.print("J");
				continue;
			}
			if (result[i]==11) {
				System.out.print("Q");
				continue;
			}
			if (result[i]==12) {
				System.out.print("K");
				continue;
			}else {
				System.out.print(result[i]);
			}	
		}
	}	
}

猜你喜欢

转载自blog.csdn.net/TNTZS666/article/details/86567559
今日推荐