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