Count subarrays made up of elements having exactly K set bits | Java program for the above approach ; 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
import java . util . * ; class GFG { static int countSet ( int N ) { int ans = 0 ; while ( N > 0 ) { ans += N & 1 ; N >>= 1 ; } return ans ; } static int countSub ( int [ ] arr , int k ) { int ans = 0 ; int setK = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { if ( countSet ( arr [ i ] ) == k ) setK += 1 ; else setK = 0 ; ans += setK ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 1 , 5 , 6 } ; int K = 2 ; System . out . print ( countSub ( arr , K ) ) ; } }