text: Sum of bit differences for numbers from 0 to N | 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
code: function binpow ( a , b ) { let res = 1 ; while ( b ) { if ( b & 1 ) res = res * a ; a = a * a ; b = Math . floor ( b / 2 ) ; } return res ; } function find ( x ) { if ( x == 0 ) return 0 ; let p = Math . log2 ( x ) ; return binpow ( 2 , p + 1 ) - 1 ; } function getBinary ( n ) { let ans = " " ; while ( n ) { let dig = n % 2 ; ans += String ( dig ) ; n = Math . floor ( n / 2 ) ; } return ans ; } function totalCountDifference ( n ) { let ans = getBinary ( n ) ; let req = 0 ; for ( let i = 0 ; i < ans . length ; i ++ ) { if ( ans [ i ] == ' ' ) { req += find ( binpow ( 2 , i ) ) ; } } return req ; } let N = 5 ; document . write ( totalCountDifference ( N ) ) ;