[HackerRank] Diagonal Difference

Problem

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

Input Format

The first line contains a single integer, N. The next N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns.

Output Format

Print the absolute difference between the two sums of the matrix's diagonals as a single integer.

Sample Input

311    2     44     5     610    8     -12

Sample Output

15

Explanation

The primary diagonal is:

11      5            -12

Sum across the primary diagonal: 11 + 5 - 12 = 4

The secondary diagonal is:

            4      510

Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15

Solution

import java.io.*;import java.util.*;public class Solution {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int n = in.nextInt();        int pSum = 0, sSum = 0;        int a[][] = new int[n][n];        for(int i = 0; i < n; i++){            for(int j = 0; j < n; j++){                a[i][j] = in.nextInt();            }        }        for(int i=0; i<n; i++){            pSum += a[i][i];            sSum += a[i][n-1-i];        }        int sum = Math.abs(pSum - sSum);        System.out.println(sum);    }}

关键字:java, matrix, int, the


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部