We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
It relies on the fact that for each element in the first diagonal, the index difference (starting from 0) is a = matrixSize + 1 and on the second diagonal, the index difference between each element is b = matrixSize - 1.
The "j != 0 && j != (size * size) - 1" in the second if statement checks if the current index is not the first or the last, because these indexes are always multiples of both a and b, which causes superfluous addition to b.
#include<iostream>usingnamespacestd;intmain(){intsize;cin>>size;intdiagonal1=0;intdiagonal2=0;// Current indexintj=0;// Index distance between elements on D1intd1Gap=size+1;// Index distance between elements on D2intd2Gap=size-1;for(inti=0;i<size*size;i++){intnumber;cin>>number;if(j==0||j%d1Gap==0){diagonal1+=number;}if(j%d2Gap==0&&j!=0&&j!=(size*size)-1){diagonal2+=number;}j++;}cout<<abs(diagonal1-diagonal2);return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Diagonal Difference
You are viewing a single comment's thread. Return to all comments →
C++ without array approach
It relies on the fact that for each element in the first diagonal, the index difference (starting from 0) is a = matrixSize + 1 and on the second diagonal, the index difference between each element is b = matrixSize - 1.
The "j != 0 && j != (size * size) - 1" in the second if statement checks if the current index is not the first or the last, because these indexes are always multiples of both a and b, which causes superfluous addition to b.