Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
592 B
2
Indexable
Never
// My 1st soluation


var diagonalSum = function(mat) {
    let len =  mat.length
    let sum = 0
    for(let i = 0; i < len;i++) {
        for(let j = 0; j < len; j++) {
            if (i == j || (i+j) == (len-1)) {
                sum += mat[i][j]
            }
        }
    }
    return sum
};

// 2nd soluation
var diagonalSum = function(mat) {
    let len =  mat.length
    let sum = 0
    for(let i = 0; i < len;i++) {
        sum += mat[i][i] + mat[i][len - i -1]
    }
    if (len%2 !== 0) {
        let mid = parseInt(len/2)
        sum -= mat[mid][mid]
    }
    return sum
};