楊輝三角形 隔行對齊

今天接觸了個招聘的,先要寫個楊輝三角形 並隔行對齊

 

所以就臨時寫了個(當然也借鑑了網上的資源~~~~~)

 

大約用了20分鐘。。。。

 

總結: 先把3行的隔行對齊弄出來 多行的也就ok了


public class YangHuiSJ {
    public static void main(String[] args) {
        int row = 30;
        int[][] a = new int[row][row];
        for (int i = 0; i < row; i++)
            for (int j = 0; j < row; j++) {
                if (j < i) {
                    a[i][j] = 1;
                    if (j == 0) {
                        a[i][j] = 1;
                    } else {
                        a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
                    }
                } else {
                    a[i][j] = 1;
                }
            }

        for (int i = 0; i < row; i++) {
            for (int x = 0; x <row-i; x++) {
                System.out.print("         ");
            }
            for (int j = 0; j <= i; j++) {
                System.out.printf("%9d",a[i][j]);
                System.out.print("         ");
            }
            System.out.printf("/n");
        }
    }
}

發佈了43 篇原創文章 · 獲贊 3 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章