Sum of bit differences for numbers from 0 to N | Python3 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 ; Given Number ; Function Call
from math import log NEW_LINE def binpow ( a , b ) : NEW_LINE INDENT res = 1 NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT res = res * a NEW_LINE DEDENT a = a * a NEW_LINE b //= 2 NEW_LINE DEDENT return res NEW_LINE DEDENT def find ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT p = log ( x ) / log ( 2 ) NEW_LINE return binpow ( 2 , p + 1 ) - 1 NEW_LINE DEDENT def getBinary ( n ) : NEW_LINE INDENT ans = " " NEW_LINE while ( n > 0 ) : NEW_LINE INDENT dig = n % 2 NEW_LINE ans += str ( dig ) NEW_LINE n //= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT def totalCountDifference ( n ) : NEW_LINE INDENT ans = getBinary ( n ) NEW_LINE req = 0 NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT if ( ans [ i ] == '1' ) : NEW_LINE INDENT req += find ( binpow ( 2 , i ) ) NEW_LINE DEDENT DEDENT return req NEW_LINE DEDENT N = 5 NEW_LINE print ( totalCountDifference ( N ) ) NEW_LINE