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]]
符合预期的结果
标签:pyramid,Java,int,练习,基础,System,Arrays,deepToString,out 来源: https://blog.csdn.net/qq_43182276/article/details/120355267