Java基础练习

1、编写一个函数,当给定一个数字>= 0时,返回一个由升序长度子数组组成的Array  

(Write a function that when given a number >= 0, returns an Array of ascending length subarrays.)
pyramid(0) => [ ] pyramid(1) => [ [1] ]
 pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]

   public static int[][] pyramid(int n){
        int[][] arr = new int[n][n];

        for (int i = 1; i <= n; i++) {
            int[] temp = new int[i];
            for (int j = 0; j <= i - 1; j++) {
                temp[j] = 1;
            }
            arr[i - 1] = temp;
        }
        return arr;
    }

代码的测试 :

System.out.println(Arrays.deepToString(pyramid(3)));
System.out.println(Arrays.deepToString(pyramid(0)));
System.out.println(Arrays.deepToString(pyramid(5)));
System.out.println(Arrays.deepToString(pyramid(1)));
System.out.println(Arrays.deepToString(pyramid(2)));

测试结果:

[[1], [1, 1], [1, 1, 1]]
[]
[[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]
[[1]]
[[1], [1, 1]]

符合预期的结果

上一篇:Java | Arrays类的基本认识和使用


下一篇:java随手记 基础