Java经典编程题50道之四十八

时间:2023-03-09 18:55:31
Java经典编程题50道之四十八

某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下: 每位数字都加上5,然后用和除以10的余数代替该数字, 再将第一位和第四位交换,第二位和第三位交换。

public class Example48 {
    public static void main(String[] args) {
        f(2345);
    }

public static void f(int num) {
        int[] c = new int[4];
        if (num > 999 && num < 10000) {
            c[0] = num / 1000;
            c[1] = (num / 100) % 10;
            c[2] = (num / 10) % 10;
            c[3] = num % 10;
            for (int j = 0; j < 4; j++) {
                c[j] += 5;
                c[j] %= 10;
            }
            for (int j = 0; j <= 1; j++) {
                int temp = c[j];
                c[j] = c[3 - j];
                c[3 - j] = temp;
            }
            System.out.print("加密后的数字为:");
            for (int j = 0; j < 4; j++)
                System.out.print(c[j]);
        } else {
            System.out.println("传输的数据有错,请重试!!!");
        }
    }
}