Java基础练习

2021/9/17 22:07:48

本文主要是介绍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基础练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程