Count total unset bits in all the numbers from 1 to N | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countUnsetBits ( int n ) { int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = i ; while ( temp ) { if ( temp % 2 == 0 ) cnt ++ ; temp = temp / 2 ; } } return cnt ; } int main ( ) { int n = 5 ; cout << countUnsetBits ( n ) ; return 0 ; }