zoukankan      html  css  js  c++  java
  • 杨辉三角

    题目:使用二维数组打印一个10行杨辉三角。

    思路:

    本题考察数组元素的赋值。

    1. 第一行有1个元素,第n行有n个元素

    2.每一行的第一个元素和最后一个元素都是1

    3.从第三行开始,对于非第一个元素和最后一个元素的元素,即:yangHui[i][j] = yangHui[i-1][j-1] + yangHui[i-1][j]; 

    代码实现:

    public class test{
        public static void main(String[] args) {
            int[][] yangHui = new int[10][];
            for (int i = 0; i < yangHui.length; i++) {
                yangHui[i] = new int[i + 1];
    
                // 给首末元素赋值
                yangHui[i][0] = yangHui[i][i] = 1;
                // 给每行的非首末元素赋值
                for (int j = 1; j < yangHui[i].length - 1; j++) {
                    yangHui[i][j] = yangHui[i-1][j-1] + yangHui[i-1][j];
                }
    
            }
            // 二维数组的遍历
            for (int i = 0; i < yangHui.length; i++) {
                for (int j = 0; j < yangHui[i].length; j++) {
                    System.out.print(yangHui[i][j] + " ");
                }
                System.out.println();
            }
        }
    }

    运行结果:

    【拓展之笔试题】

    创建一个长度为6的int型数组,要求数组元素的值都在1-30之间,且是随机赋值。同时,要求元素的值各不相同。

    噗.....半个小时才做出来T.T,各不相同一直没找到解决方案。。。

    解法1(自己写的)

    public class test{
        public static void main(String[] args) {
            int[] arr = new int[6];
            arr[0] = (int)(Math.random() * 30) + 1; // [0,1) [0,30) [1,31)
            int index = 1;
            while (index < arr.length){
                boolean flag = false;
                int temp = (int)(Math.random() * 30) + 1;
                for (int i = 0; i < index; i++) {
                    if (temp == arr[i]){
                        flag = true;
                        break;
                    }
                }
                if (!flag){
                    arr[index] = temp;
                    index++;
                }
            }
            System.out.println(Arrays.toString(arr));
        }
    }

    解法2(参考康师傅)

    public class test{
        public static void main(String[] args) {
            int[] arr = new int[6];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = (int)(Math.random() * 30) + 1; // [0,1) [0,30) [1,31)
                for (int j = 0; j < i; j++) {
                    if (arr[i] == arr[j]){
                        i--;  // 妙极了~~
                        break;
                    }
                }
            }
            System.out.println(Arrays.toString(arr));
        }
    }
  • 相关阅读:
    c++调用lua
    HTTP实现长连接(TTP1.1和HTTP1.0相比较而言,最大的区别就是增加了持久连接支持Connection: keep-alive)
    C++: std::string 与 Unicode 如何结合?
    统计一下你写过多少代码
    解读jQuery中extend函数
    C#如何通过SOCKET的方式获取HTTPONLY COOKIE
    Java进阶代码
    SQLSERVER聚集索引与非聚集索引的再次研究(上)
    c,c++函数返回多个值的方法
    COM思想的背后
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13675336.html
Copyright © 2011-2022 走看看