我在编写对角线差分代码时刚开始编程,我想出了这种方法,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int j = 0;
int a[][] = new int[n][n];
int count1 = 0; int count2 = 0;
int result = 0;
for(int a_i=0; a_i < n; a_i++){
for(int a_j = 0;a_j < n;a_j++){
a[a_i][j] = in.nextInt();
}}
for(int i = 0;i<n;i++)
{
count1+=a[i][j];
System.out.println(count1);
j++;
}
j = 0;
for(int i = n-1;i>=0;i--)
{
count2+=a[i][j];
System.out.println(count2);
j++;
}
result = Math.abs(count1 - count2);
System.out.println(result);
}
输入
3
11 2 4
4 5 6
10 8 -12
预期产出 15
我的输出 16
最佳答案
为什么有这么多变通办法? 你需要一个非常小的代码:
for(int i = 0;i<n;i++){
count1+=a[i][i];
count2+=a[i][n-1-i];
}
关于java - 对角差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46724424/