-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixDiagonalSum.java
More file actions
42 lines (35 loc) · 924 Bytes
/
MatrixDiagonalSum.java
File metadata and controls
42 lines (35 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class MatrixDiagonalSum {
public int diagonalSum(int[][] mat) {
int i = 0;
int j = 0;
int leftSum = 0;
int rightSum = 0;
while ((i < mat.length) && (j < mat.length)) {
leftSum += mat[i][j];
i++;
j++;
}
i = 0;
j = mat.length - 1;
while ((i < mat.length) && (j >= 0)) {
if(i==j ) {
i++;
j--;
continue;
};
rightSum += mat[i][j];
i++;
j--;
}
return leftSum + rightSum;
}
public static void main(String[] args) {
MatrixDiagonalSum matrixDiagonalSum = new MatrixDiagonalSum();
int[][] mat = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrixDiagonalSum.diagonalSum(mat));
}
}