Count pairs with set bits sum equal to K | 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
def countSetBits ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) ; NEW_LINE count += 1 NEW_LINE DEDENT return count ; NEW_LINE DEDENT def pairs ( arr , n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = countSetBits ( arr [ i ] ) + countSetBits ( arr [ j ] ) ; NEW_LINE if ( sum == k ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 4 ; NEW_LINE print ( pairs ( arr , n , k ) ) ; NEW_LINE DEDENT