Count subarrays made up of elements having exactly K set bits | Function to count the number of set bits in an integer N ; Stores the count of set bits ; While N is non - zero ; If the LSB is 1 , then increment ans by 1 ; Return the total set bits ; Function to count the number of subarrays having made up of elements having K set bits ; Stores the total count of resultant subarrays ; Traverse the given array ; If the current element has K set bits ; Otherwise ; Increment count of subarrays ; Return total count of subarrays ; Driver Code ; Function Call
def countSet ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE while N : NEW_LINE INDENT ans += N & 1 NEW_LINE N >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def countSub ( arr , k ) : NEW_LINE INDENT ans = 0 NEW_LINE setK = 0 NEW_LINE for i in arr : NEW_LINE INDENT if countSet ( i ) == k : NEW_LINE INDENT setK += 1 NEW_LINE DEDENT else : NEW_LINE INDENT setK = 0 NEW_LINE DEDENT ans += setK NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 5 , 6 ] NEW_LINE K = 2 NEW_LINE print ( countSub ( arr , K ) ) NEW_LINE