Today I was training algorithms and data structures on hackerrank.com. Here is one example:
Given a square matrix of size NxN, calculate the absolute difference between the sums of its diagonals.
import java.util.Scanner;
public class DiagonalAbsoluteSum {
static int sumA = 0;
static int sumB = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][n];
for (int a_i = 0; a_i < n; a_i++) {
for (int a_j = 0; a_j < n; a_j++) {
a[a_i][a_j] = in.nextInt();
}
}
for (int i = 0; i < a.length; i++) {
sumA += a[i][i];
}
for (int i = 0; i < a.length; i++) {
sumB += a[i][a.length - i - 1];
}
System.out.println(Math.abs(sumA - sumB));
}
}
No comments:
Post a Comment