본문 바로가기

문제풀이/C 문제풀이

[HackerRank]Diagonal Difference

문제

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

Function description
Complete the diagonal Difference function in the editor below. It must return an integer representing the absolute diagonal difference.
Input Format
The first line contains a single integer, , the number of rows and columns in the matrix .
Each of the next lines describes a row, , and consists of space-separated integers .
Output Format
Print the absolute difference between the sums of the matrix's two diagonals as a single integer.

CODE

int diagonalDifference(int arr_rows, int arr_columns, int** arr) {
    int sum=0; // 전체 합계를 정의한다
    for(int i=0, j;i<arr_rows;i++, j++)
        sum += (arr[i][j]-arr[i][arr_columns-1-j]);
// 한 행에서 왼쪽 대각선에 해당하는 원소는 더하고 오른쪽 대각선에 해당하는 원소는 뺀다
// 인덱스는 0부터 arr_columns-1 부터임을 잊지 말자
    return sum > 0 ? sum : sum*(-1); //sum의 절댓값을 구한다
}

감상

최대한 간단하게 만들려고 노력했다. 더 간단하게 만들려면 arr_rows의 반까지만 for문으로 돌리고, 더하고 빼는 원소의 개수를 두 배로 늘려도 괜찮을 것 같다

'문제풀이 > C 문제풀이' 카테고리의 다른 글

[HackerRank]Staircase  (0) 2019.05.26
[HackerRank]Plus Minus  (0) 2019.05.24
[Hackerrank]A Very Big Sum  (0) 2019.05.20
[Hackerrank]Compare the Triplets  (0) 2019.05.17
[HackerRank]Simple Array Sum  (0) 2019.05.17