[HackerRank]Diagonal Difference

jh Seo·2024년 2월 4일
0

HackerRank

목록 보기
5/15

개요

[HackerRank]Diagonal Difference

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

For example, the square matrix is shown below:

1 2 3
4 5 6
9 8 9
The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .

접근 방식

대각선의 값들을 더한 후 비교하면 되는 간단한 문제이다.

전체 코드

/*
 * Complete the 'diagonalDifference' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts 2D_INTEGER_ARRAY arr as parameter.
 */

int diagonalDifference(vector<vector<int>> arr) {
    int lToR=0,rToL=0;
    for(int i=0;i<arr.size();i++){
        lToR += arr[i][i];
    }
    for(int i=0;i<arr.size();i++){
        rToL += arr[arr.size()-i-1][i];
    }
    return lToR>rToL? lToR-rToL : rToL-lToR;
}
profile
코딩 창고!

0개의 댓글