n (1 ~ 99999)// 原代碼用 if-else 鏈判斷位數區間
if (a >= 0 && a <= 9) // 1位
else if (a >= 10 && a <= 99) // 2位
// ... 重複代碼
缺點:硬編碼區間、代碼重複、擴展性差 (超過 5 位需加分支)。
import java.util.Scanner;
public class ReverseDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入正整數 (1-99999): ");
long n = sc.nextLong();
if (n <= 0 || n > 99999) {
System.out.println("輸入超出範圍");
return;
}
// 1. 計算位數 (數學法)
int digits = (int)Math.log10(n) + 1;
// 或字符串法: String.valueOf(n).length()
// 2. 逆序輸出 (字符串法最簡潔)
String reversed = new StringBuilder(String.valueOf(n)).reverse().toString();
System.out.println(n + " 是 " + digits + " 位數");
System.out.println("逆序輸出: " + reversed);
}
}
public class ReverseDigitsMath {
public static void main(String[] args) {
long n = 12345;
int digits = 0;
long temp = n;
// 計算位數
while (temp > 0) {
temp /= 10;
digits++;
}
System.out.println(n + " 是 " + digits + " 位數");
System.out.print("逆序: ");
// 逆序輸出各位
temp = n;
while (temp > 0) {
System.out.print(temp % 10);
temp /= 10;
}
System.out.println();
}
}
public class ReverseDigitsGeneric {
public static void process(String numStr) {
// 驗證純數字
if (!numStr.matches("\\d+") || numStr.startsWith("0")) {
System.out.println("無效輸入");
return;
}
int digits = numStr.length();
String reversed = new StringBuilder(numStr).reverse().toString();
System.out.println("位數: " + digits);
System.out.println("逆序: " + reversed);
}
public static void main(String[] args) {
process("12345678901234567890"); // 超過 long 範圍也能處理
}
}
原代碼用「區間判斷 + 硬編碼分支」處理位數,違反 DRY 原則。數學法 log10(n)+1 或字符串法 length() 可統一處理任意位數。逆序輸出用 StringBuilder.reverse() 最簡潔;教學理解可用 %10 /10 循環。實際開發中,**字符串處理數字位操作往往比數學運算更簡潔、更安全、無溢出風險**。