题目
某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密 规则如下:
每位数字都加上 5,然后用和除以 10 的余数代替该数字,再将第一位和第四位交 换,第二位和第三位交换。
将输入的数从后往前读到数组里,再进行交换
import java.util.Scanner;
public class Problem48 {
public static void main(String[] args) {
System.out.println("请输入一个四位的整数:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
while((number<1000)||(number>9999)){
System.out.println("不在范围内,请重新输入:");
number = scan.nextInt();
}
scan.close();
System.out.print("加密后:"+encryption( number));
}
public static int encryption( int n ){
int[] arr = new int[4];
for (int i = 3; i >=0 ; i--) { //将n的每位数输入至arr数组
arr[i]= (n%10+5)%10; //从个位起, 加五余10
n /=10;
}
//第一位和第四位交 换,第二位和第三位交换
swap(arr,0,3);
swap(arr,1,2);
int code = 0;
for (int i = 0; i <arr.length ; i++) {
// System.out.println(arr[i]);
code = code *10+arr[i];
}
return code;
}
// swap
static void swap (int[] a, int x , int y){
int temp = a[x];
a[x]=a[y];
a[y]=temp;
}
}
结果如下: