4个算法题

今天刷正在快乐的刷抖音,然后刷到了这个
在这里插入图片描述
我想了几分钟,第一题,去年蓝桥杯遇到过,到现在我也没主动寻找答案,太懒惰了。第二题,额,循环。我只能想到这个。第三题,感觉暴力循环都不好写。难受,直接上答案吧:

    //1.求n的阶乘末尾0的个数
    public static int trailingZeroes(int n) {
        int count = 0;
        while (n > 0) {
            count += n / 5;
            n /= 5;
        }
        return count;
    }
    //2.求x的y次幂
    public static double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }
        if (n == -1) {
            return 1 / x;
        }
       // double res = 1;
       // for (int i = n; i != 0; i /= 2) {
       //     if (i % 2 != 0) {
       //         res *= x;
       //     }
       //     x *= x;
      //  }
     // return res;
        double half = myPow(x, n / 2);
        double rest = myPow(x, n % 2);
        return half * half * rest;
 
    }
    //3.把一个数组分成两个数组,使得两个数组的和的差最小
    public static int minDifference(int[] nums) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        int n = nums.length;
        int[][] dp = new int[n + 1][sum / 2 + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum / 2; j++) {
                if (j >= nums[i - 1]) {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - nums[i - 1]] + nums[i - 1]);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return sum - 2 * dp[n][sum / 2];
    }

室友又问我怎么输出:
123
894
765
这种回型矩阵图形。

 //4.输入n,输出下面的图形,按回型顺序输出,返回一个二维数组
    public static int[][] print2(int n) {
        int[][] arr = new int[n][n];
        int count = 1;
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        while (count <= n * n) {
            for (int i = left; i <= right; i++) {
                arr[top][i] = count++;
            }
            top++;
            for (int i = top; i <= bottom; i++) {
                arr[i][right] = count++;
            }
            right--;
            for (int i = right; i >= left; i--) {
                arr[bottom][i] = count++;
            }
            bottom--;
            for (int i = bottom; i >= top; i--) {
                arr[i][left] = count++;
            }
            left++;
        }
        return arr;
    }

okk今天就到这里了,上图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JJpZh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值