面對「打印菱形、三角形、金字塔」這類經典編程練習,很多初學者陷入「死記模板」的誤區。實則掌握核心思維框架,就能舉一反三解決所有幾何圖形打印問題。
將圖形映射到二維坐標系(行號i,列號j):
i行:空格數 = |中間行 - i|,星號數 = 總寬度 - 2*空格數將觀察到的規律轉化為數學表達式:
| 圖形類型 | 行號範圍 | 星號數公式 | 空格數公式 |
|---|---|---|---|
| 等腰三角形 | 1~n | 2*i-1 | n-i |
| 菱形 | 1~2n-1 | 2*min(i, 2n-i)-1 | |n-i| |
| 倒三角形 | 1~n | 2*(n-i+1)-1 | i-1 |
for (int i = 1; i <= totalRows; i++) {
// 1. 計算當前行屬性
int spaces = calculateSpaces(i);
int stars = calculateStars(i);
// 2. 輸出空格
for (int j = 0; j < spaces; j++) System.out.print(" ");
// 3. 輸出星號
for (int j = 0; j < stars; j++) System.out.print("*");
// 4. 換行
System.out.println();
}
利用Math.abs()或對稱性質消除if-else分支:
int mid = (totalRows + 1) / 2;
int distance = Math.abs(i - mid); // 到中間行的距離
int stars = 2 * (mid - distance) - 1;
int spaces = distance;
掌握這套「觀察→建模→實現」的通用框架,不僅能應對面試刷題,更能鍛養程序員將具體問題抽象為數學模型的核心能力。