Count total set bits in all numbers from 1 to n |  ; ans store sum of set bits from 0 to n ; while n greater than equal 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 ; Driver program
public class GFG { static int countSetBits ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { boolean k = false ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { if ( k == true ) ans += 1 ; else ans += 0 ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } public static void main ( String [ ] args ) { int n = 17 ; System . out . println ( countSetBits ( n ) ) ; } }