题目:
给出一个N*N的二维整数数组,计算主对角线元素和和副对角线和之间的差。
Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15
我的解答:
import java.io.*;
import java.util.*;
public class DiagonalDifference{
public static void main(String[] args){
//input
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
scan.nextLine();
int arr[][] = new int[N][N];
for(int i = 0; i < N; i++){
for(int j = 0; j < N;j++){
arr[i][j] = scan.nextInt();
}
if(scan.hasNextLine()){ // 如果不写这一行就会
scan.nextLine();
}
}
//calculate
int primaryDiagonal = 0;
for(int i = 0 ; i < N; i++){
primaryDiagonal += arr[i][i];
}
int secondaryDiagonal = 0;
for(int i = 0; i < N; i++){
secondaryDiagonal += arr[i][N - i - 1];
}
int result = primaryDiagonal - secondaryDiagonal;
result = (result < 0) ? (-result) : result;
System.out.println(result);
scan.close();
}
}