Question
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
Ans : | (1+5+9) – (3+5+9) | = 2.
Solution
static int diagonalDifference(int[][] arr) { int diagonalSum1 = 0; int diagonalSum2 = 0; int length = arr.length; for (int row = 0; row < length; row++){ diagonalSum1 += arr[row][row]; diagonalSum2 += arr[row][length - row - 1]; } return Math.abs(diagonalSum1 - diagonalSum2); }