text: Sum of bit differences for numbers from 0 to N | C ++ program for the above approach ; Function to implement fast exponentiation ; Function to return the value for powers of 2 ; Function to convert N into binary ; To store binary representation ; Iterate each digit of n ; Return binary representation ; Function to find difference in bits ; Get binary representation ; total number of bit differences from 0 to N ; Iterate over each binary bit ; If current bit is '1' then add the count of current bit ; Driver Code ; Given Number ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int binpow ( int a , int b ) { int res = 1 ; while ( b ) { if ( b & 1 ) res = res * a ; a = a * a ; b /= 2 ; } return res ; } int find ( int x ) { if ( x == 0 ) return 0 ; int p = log2 ( x ) ; return binpow ( 2 , p + 1 ) - 1 ; } string getBinary ( int n ) { string ans = " " ; while ( n ) { int dig = n % 2 ; ans += to_string ( dig ) ; n /= 2 ; } return ans ; } int totalCountDifference ( int n ) { string ans = getBinary ( n ) ; int req = 0 ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { if ( ans [ i ] == '1' ) { req += find ( binpow ( 2 , i ) ) ; } } return req ; } int main ( ) { int N = 5 ; cout << totalCountDifference ( N ) ; return 0 ; }