輸入數字 a (0-9) 和項數 n,計算 S = a + aa + aaa + ... (n項)。例:a=2, n=5 → 2+22+222+2222+22222。
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 項數
String a = sc.next(); // 數字字符
String term = "";
long sum = 0;
for (int i = 0; i < n; i++) {
term += a; // "2" → "22" → "222" ...
sum += Long.parseLong(term);
}
System.out.println(sum);
直觀易懂,利用字符串拼接構造每一項。
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
long term = 0, sum = 0;
for (int i = 0; i < n; i++) {
term = term * 10 + a; // 2 → 22 → 222 ...
sum += term;
System.out.println("第" + (i+1) + "項: " + term);
}
System.out.println("總和: " + sum);
核心遞推公式:T_k = T_{k-1} * 10 + a,避免字符串解析,效率更高,無大數溢出風險(配合 BigInteger 可任意精度)。
BigInteger term = BigInteger.ZERO, sum = BigInteger.ZERO;
BigInteger A = BigInteger.valueOf(a);
for (int i = 0; i < n; i++) {
term = term.multiply(BigInteger.TEN).add(A);
sum = sum.add(term);
}