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
function countSet ( N ) { let ans = 0 ; while ( N ) { ans += N & 1 ; N >>= 1 ; } return ans ; } function countSub ( arr , k ) { let ans = 0 ; let setK = 0 ; for ( let i = 0 ; i < 5 ; i ++ ) { if ( countSet ( arr [ i ] ) == k ) setK += 1 ; else setK = 0 ; ans += setK ; } return ans ; } let arr = [ 4 , 2 , 1 , 5 , 6 ] ; let K = 2 ; document . write ( ( countSub ( arr , K ) ) ) ;