Sum of numbers obtained by the count of set and non | CPP program for the above approach ; Functino to find the number after processing the diagonal elements ; Store the required number ; Checking for each position ; Store the number of set bits & non - set bits at position i ; Traverse the diagonal elements ; Update count of S if current element is set at position i ; Else update NS ; If number of set bits is > number of non - set bits , add set bits value to the ans ; Return the answer ; Function to find the sum of the numbers generated after processing both the diagonals of the matrix ; Store the primary diagonal elements ; Store the secondary diagonal elements ; Function Call to get the required numbers and return their sum ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int processDiagonal ( vector < int > arr ) { int ans = 0 ; int getBit = 1 ; for ( int i = 0 ; i < 32 ; i ++ ) { int S = 0 ; int NS = 0 ; for ( auto j : arr ) { if ( getBit & j ) S += 1 ; else NS += 1 ; } if ( S > NS ) ans += pow ( 2 , i ) ; getBit <<= 1 ; } return ans ; } int findSum ( vector < vector < int > > mat ) { int i = 0 ; int j = 0 ; vector < int > priDiag ; while ( i < mat . size ( ) ) { priDiag . push_back ( mat [ i ] [ j ] ) ; i += 1 ; j += 1 ; } i = 0 ; j = mat . size ( ) - 1 ; vector < int > secDiag ; while ( i < mat . size ( ) ) { secDiag . push_back ( mat [ i ] [ j ] ) ; i += 1 ; j -= 1 ; } return processDiagonal ( priDiag ) + processDiagonal ( secDiag ) ; } int main ( ) { vector < vector < int > > mat { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; cout << findSum ( mat ) << endl ; }