Tuesday, March 2, 2021

Leetcode Everyday: 1572. Matrix Diagonal Sum. Easy

public class Solution {
    public int DiagonalSum(int[][] mat) {
        var sum = 0;        
     
        var length = mat.Length;
        for (var walk = 0; walk < length; ++walk) {
            sum += mat[walk][walk] + mat[^(walk + 1)][walk];
        }   
        
        // exclude center
        var center = Math.DivRem(length, 2, out int remainder);
        if (remainder == 1) {
            sum -= mat[center][center];
        }           
  
        return sum;
    }
}
Source: https://leetcode.com/problems/matrix-diagonal-sum/

No comments:

Post a Comment