規則:輸入 8 位正整數,每位加 6 取模 10,再對稱交換(1↔8, 2↔7, 3↔6, 4↔5)。
import java.util.Scanner;
public class EightDigitEncrypt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
do {
System.out.print("請輸入八位正整數:");
num = sc.nextInt();
} while (num < 10_000_000 || num > 99_999_999);
int[] d = new int[8];
d[0] = num / 10_000_000;
d[1] = (num / 1_000_000) % 10;
d[2] = (num / 100_000) % 10;
d[3] = (num / 10_000) % 10;
d[4] = (num / 1_000) % 10;
d[5] = (num / 100) % 10;
d[6] = (num / 10) % 10;
d[7] = num % 10;
// 加 6 取模
for (int i = 0; i < 8; i++) d[i] = (d[i] + 6) % 10;
// 對稱交換
for (int i = 0; i < 4; i++) swap(d, i, 7 - i);
System.out.print("加密後:");
for (int v : d) System.out.print(v);
System.out.println();
}
static void swap(int[] a, int i, int j) { int t=a[i]; a[i]=a[j]; a[j]=t; }
}
public class DigitEncryptor {
public static int[] encrypt(int[] digits, int addend) {
int n = digits.length;
int[] res = digits.clone();
for (int i = 0; i < n; i++) res[i] = (res[i] + addend) % 10;
for (int i = 0; i < n/2; i++) swap(res, i, n-1-i);
return res;
}
public static int[] decrypt(int[] encrypted, int addend) {
// 解密:先交換(自逆),再加 (10-addend) 取模
int[] res = encrypted.clone();
for (int i = 0; i < res.length/2; i++) swap(res, i, res.length-1-i);
for (int i = 0; i < res.length; i++) res[i] = (res[i] + (10 - addend)) % 10;
return res;
}
static void swap(int[] a, int i, int j) { int t=a[i]; a[i]=a[j]; a[j]=t; }
}
支援任意長度與加數,展示對稱加密「加密即解密」的自逆性質(交換步驟)。