Java算法练习题
发布网友
发布时间:2022-05-16 01:49
我来回答
共2个回答
热心网友
时间:2023-10-08 21:17
我就直接根据你提供的数组数值来了,没有打注释,有什么不懂的可以继续追问。
public class ThreeSum {
public static void main(String[] argv) {
int a[][] = {
{ 259, 132, 799, 113 },
{ 332, 262, 209, 863 },
{ 807, 301, 684, 343 }
};
int[] b = new int[12];
int max;
int index = 0;
for ( int i = 0; i < 3; i++ ) {
for ( int j = 0; j < 4; j++ ) {
b[index++] = sum(a[i][j]);
}
}
max = b[0];
index = 0;
for ( int i = 1; i < 12; i++ ) {
if ( max < b[i] ) {
max = b[i];
index = i;
}
}
System.out.println("数字之和最大的数为: " + max);
System.out.printf("该数组的位置为: a[%d][%d]\n", index / 4, index % 4);
}
public static int sum(int a) {
return (int)( ( a / 100 ) + ( ( a % 100) / 10 ) + ( a % 10 ) );
}
}
结果图如下:
热心网友
时间:2023-10-08 21:17
import java.util.Arrays;
import java.util.Random;
public class SuanFa1 {
static int[][]arr = null;
static int[][]arr2;
static int[] sum;
static int a;
static int b;
static int c;
public static void main(String[] args) {
getArray(3, 4);
}
private static void getArray(int m, int n) {
arr = new int [m][n];
arr2 = new int [m][n];
sum = new int [m*n];
int k = 0;
System.out.println("生成的二维数组为:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = new Random().nextInt(900)+100;
System.out.print(arr[i][j] + " ");
a = arr[i][j]/100;
b = arr[i][j]/10 % 10;
c = arr[i][j] % 10;
arr2[i][j] = a+b+c;
sum[k++] = arr2[i][j];
}
System.out.println();
}
System.out.println("------------------------------------");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
//System.out.print(arr2[i][j] + " ");
if (arr2[i][j] > k) {
k = arr2[i][j];
Arrays.sort(sum);
if(k == sum[m*n-1])
System.out.print("每位数字相加最大值的数是:arr[" + i + "][" + j + "]");
}
}
System.out.println();
}
}
}