將整數按位拆解是基礎算法訓練常客。本文提供從固定位數到任意長度的通用解法,並展示一個支援萬億級、帶中文單位輸出的完整控制台交互程序。
int num = 53;
int ge = num % 10; // 3
int shi = (num / 10) % 10; // 5
int bai = num / 100; // 0
規律:第 n 位 (0-index) = (num / 10^n) % 10
public static List<Integer> splitDigits(long num) {
List<Integer> digits = new ArrayList<>();
if (num == 0) { digits.add(0); return digits; }
boolean negative = num < 0;
num = Math.abs(num);
while (num > 0) {
digits.add(0, (int)(num % 10)); // 头插保持高位在前
num /= 10;
}
if (negative) digits.add(0, -1); // 标记负号
return digits;
}
import java.util.Scanner;
public class NumberSplitter {
private static final String[] UNITS =
{"", "十", "百", "千", "萬", "十萬", "百萬", "千萬", "億", "十億", "百億", "千億", "萬億"};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入一個整數 (支援 ±9999 億): ");
long num = sc.nextLong();
sc.close();
if (num == 0) { System.out.println("個位: 0"); return; }
boolean neg = num < 0;
num = Math.abs(num);
int pos = 0;
while (num > 0) {
int digit = (int)(num % 10);
String unit = (pos < UNITS.length) ? UNITS[pos] : "10^" + pos;
System.out.printf("%s位 (%s): %d%n", unit.isEmpty()?"個":unit, unit, digit);
num /= 10;
pos++;
}
if (neg) System.out.println("符號: 負數");
}
}
請輸入一個整數: 123456789
個位: 9
十位: 8
百位: 7
千位: 6
萬位: 5
十萬位: 4
百萬位: 3
千萬位: 2
億位: 1
% 10 取末位,/= 10 右移一位,循環直到 0long 支援 ±922京 (19 位),足夠大多數業務場景BigInteger 配合 divideAndRemainder