Matrix Diagonal Sum LeetCode solution in C++
1class Solution {2public:3int diagonalSum(vector<vector<int>> &mat) {4int n = mat.size();5int ans = 0;67for (int i = 0; i < n; i++) {8ans = ans + mat[i][i] + mat[i][n - i - 1];9}10ans = (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.13return ans;14}15};