Matrix Diagonal Sum LeetCode solution in C++

1
class Solution {
2
public:
3
int diagonalSum(vector<vector<int>> &mat) {
4
int n = mat.size();
5
int ans = 0;
6

7
for (int i = 0; i < n; i++) {
8
ans = ans + mat[i][i] + mat[i][n - i - 1];
9
}
10
ans = (n & 1) ? ans - mat[n / 2][n / 2]
11
: ans; // if n is odd then we have to subtract mat[n/2][n/2]
12
// from the ans because we add it twice earlier.
13
return ans;
14
}
15
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0