Count total unset bits in all the numbers from 1 to N | Java implementation of the approach ; Function to return the count of unset bits in the binary representation of all the numbers from 1 to n ; To store the count of unset bits ; For every integer from the range [ 1 , n ] ; A copy of the current integer ; Count of unset bits in the current integer ; If current bit is unset ; Driver code
class GFG { static int countUnsetBits ( int n ) { int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = i ; while ( temp > 0 ) { if ( temp % 2 == 0 ) { cnt = cnt + 1 ; } temp = temp / 2 ; } } return cnt ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( countUnsetBits ( n ) ) ; } }