Count total set bits in all numbers from range L to R | Java program for the above approach ; Function that counts the set bits from 0 to N ; To store sum of set bits from 0 - N ; Until n >= to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; Change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; Again set change to 2 ^ i ; Increment the position ; Function that counts the set bit in the range ( L , R ) ; Return the count ; Driver Code ; Given L and R ; Function Call
import java . util . * ; class GFG { static int countSetBit ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { boolean k = true ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { ans += k == true ? 0 : 1 ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } static int countSetBits ( int L , int R ) { return Math . abs ( countSetBit ( R ) - countSetBit ( L - 1 ) ) ; } public static void main ( String [ ] args ) { int L = 3 , R = 5 ; System . out . print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " + countSetBits ( L , R ) + "NEW_LINE"); } }