Count pairs with set bits sum equal to K | C # implementation of the approach ; Function to return the count of set bits in n ; Function to return the count of required pairs ; To store the count ; Sum of set bits in both the integers ; If current pair satisfies the given condition ; Driver code
using System ; public class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static int pairs ( int [ ] arr , int n , int k ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int sum = countSetBits ( arr [ i ] ) + countSetBits ( arr [ j ] ) ; if ( sum == k ) count ++ ; } } return count ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . Length ; int k = 4 ; Console . WriteLine ( pairs ( arr , n , k ) ) ; } }