Sum of numbers obtained by the count of set and non-set bits in diagonal matrix elements

• Last Updated : 11 Nov, 2021

Given a square matrix mat[][] of dimension N*N, convert the elements present in both the diagonals to their respective binary representations and perform the following operations:

• For every position of bits, count the number of set bits and non-set bits in those binary representations.
• If count of set bits exceeds that of non-set bits, place 0 at that position for a new number. Otherwise, place 1 at that position.
• Finally, print the sum of the two generated numbers.

Examples:

Input: mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: 8
Explanation:
For the primary diagonal, the binary representation of each element is:
1 = (0001)2
5 = (0101)2
9 = (1001)2
At bit position 0, number of set bits(=3)>number of non-set bits(=0)
At bit position 1, number of set bits(=0)<number of non-set bits(=3)
At bit position 2, number of set bits(=1)<number of non-set bits(=2)
At bit position 3, number of set bits(=1)<number of non-set bits(=2)
Therefore, after processing the primary diagonal, the number generated is (0001)2 = 1.
For the secondary diagonal, the binary representation of each element is:
3 = (011)2
5 = (101)2
7 = (111)2
At bit position 0, number of set bits(=3)>number of non-set bits(=0)
At bit position 1, number of set bits(=2)>number of non-set bits(=1)
At bit position 2, number of set bits(=2)>number of non-set bits(=1)
Therefore, after processing the primary diagonal, the number generated is (111)2 = 7.
Hence, the required sum = 1 + 7 = 8.

Input: mat[][] = [[2, 3], [3, 9]]
Output: 3

Naive Approach: The simplest approach is to traverse the matrix and store the primary diagonal elements in an array and the secondary diagonal elements in another array. Then find the sum of the numbers generated by iterating over the set bits of the elements in both the arrays.
Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized by finding the diagonal elements using a single loop. Follow the steps below to solve the problem:

• For Principal Diagonal elements: Iterate a loop until N, where N is the number of columns, and store mat[i][i] where i is the index variable.
• For Secondary Diagonal elements: Iterate a loop until N, where N is the number of columns and store mat[i][k], where i is the index variable and K = N – 1. Decrease K until i < N.

For finding the numbers for each set of diagonal elements, perform the following steps:

• Initialize a variable, say ans as 0, to store the resultant number.
• Iterate over the range [0, 31] using variable i and perform the following:
• Initialize S and NS as 0, to store the number of set and non-set bits respectively at position i.
• Traverse the diagonal elements using variable j and if arr[j] is set at position i, increment S by 1, else increment NS by 1.
• If the value of S is greater than NS, set the bit at position i of ans.
• After completing the above steps, the value of ans is the number generated for each set of diagonal elements.
• Repeat the above steps for the other sets of diagonal elements, and print the sum of the two numbers generated.

Below is the implementation of the above approach:

C++

 // CPP program for the above approach#includeusing namespace std; // Function to find the number after// processing the diagonal elementsint processDiagonal(vectorarr){     // Store the required number  int ans = 0;     int getBit = 1;     // Checking for each position  for (int i = 0; i < 32; i++)  {    // Store the number of set bits    // & non-set bits at position i    int S = 0;    int NS = 0;         // Traverse the diagonal elements    for(auto j: arr)    {                // Update count of S if current      // element is set at position i      if (getBit&j)        S += 1;               // Else update NS      else        NS += 1;    }    // If number of set bits is >    // number of non-set bits, add    // set bits value to the ans    if(S > NS)      ans += pow(2,i);    getBit <<= 1;   }       // Return the answer  return ans;} // Function to find the sum of the// numbers generated after processing// both the diagonals of the matrixint findSum(vector>mat){       int i = 0;  int j = 0;     // Store the primary diagonal elements  vector priDiag;     while(i secDiag;  while(i>mat{{1, 2, 3},{4, 5, 6},{7, 8, 9}}; // Function Callcout<

Java

 // Java program for the above approachimport java.util.*; class GFG{   // Functino to find the number after  // processing the diagonal elements  static int processDiagonal(ArrayList arr)  {     // Store the required number    int ans = 0;     int getBit = 1;     // Checking for each position    for (int i = 0; i < 32; i++)    {       // Store the number of set bits      // & non-set bits at position i      int S = 0;      int NS = 0;       // Traverse the diagonal elements      for(int j: arr)      {         // Update count of S if current        // element is set at position i        if ((getBit&j) != 0)          S += 1;         // Else update NS        else          NS += 1;      }      // If number of set bits is >      // number of non-set bits, add      // set bits value to the ans      if(S > NS)        ans += Math.pow(2,i);      getBit <<= 1;     }     // Return the answer    return ans;  }   // Function to find the sum of the  // numbers generated after processing  // both the diagonals of the matrix  static int findSum(int[][] mat)  {     int i = 0;    int j = 0;     // Store the primary diagonal elements    ArrayList priDiag      = new ArrayList();     while(i secDiag      = new ArrayList();    while(i

Python3

 # Python program for the above approach # Functino to find the number after# processing the diagonal elementsdef processDiagonal(arr):     # Store the required number  ans = 0     getBit = 1     # Checking for each position  for i in range(32):         # Store the number of set bits    # & non-set bits at position i    S = 0    NS = 0         # Traverse the diagonal elements    for j in arr:             # Update count of S if current      # element is set at position i      if getBit&j:        S += 1               # Else update NS      else:        NS += 1         # If number of set bits is >    # number of non-set bits, add    # set bits value to the ans    if S > NS:      ans += 2**i    getBit <<= 1       # Return the answer  return ans # Function to find the sum of the# numbers generated after processing# both the diagonals of the matrixdef findSum(mat):  i = 0  j = 0     # Store the primary diagonal elements  priDiag = []     while i

C#

 // C# program for the above approachusing System;using System.Collections.Generic; class GFG {   // Functino to find the number after  // processing the diagonal elements  static int processDiagonal(List arr)  {     // Store the required number    int ans = 0;     int getBit = 1;     // Checking for each position    for (int i = 0; i < 32; i++) {       // Store the number of set bits      // & non-set bits at position i      int S = 0;      int NS = 0;       // Traverse the diagonal elements      foreach(int j in arr)      {         // Update count of S if current        // element is set at position i        if ((getBit & j) != 0)          S += 1;         // Else update NS        else          NS += 1;      }      // If number of set bits is >      // number of non-set bits, add      // set bits value to the ans      if (S > NS)        ans += (int)Math.Pow(2, i);      getBit <<= 1;    }     // Return the answer    return ans;  }   // Function to find the sum of the  // numbers generated after processing  // both the diagonals of the matrix  static int findSum(int[, ] mat)  {     int i = 0;    int j = 0;     // Store the primary diagonal elements    List priDiag = new List();     while (i < mat.GetLength(0)) {      priDiag.Add(mat[i, j]);      i += 1;      j += 1;    }     i = 0;    j = mat.GetLength(0) - 1;     // Store the secondary diagonal elements    List secDiag = new List();    while (i < mat.GetLength(0)) {      secDiag.Add(mat[i, j]);      i += 1;      j -= 1;    }     // Function Call to get the required    // numbers and return their sum    return (processDiagonal(priDiag)            + processDiagonal(secDiag));  }   // Driver Code  public static void Main(string[] args)  {    int[, ] mat      = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };     // Function Call    Console.Write(findSum(mat));  }} // This code is contributed by ukasp.

Javascript


Output:
8

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up