Sum of consecutive bit differences of first N non | Javascript program for the above problem ; Recursive function to count the sum of bit differences of numbers from 1 to pow ( 2 , ( i + 1 ) ) - 1 ; base cases ; Recursion call if the sum of bit difference of numbers around i are not calculated ; return the sum of bit differences if already calculated ; Function to calculate the sum of bit differences up to N ; nearest smaller power of 2 ; remaining numbers ; calculate the count of bit diff ; Driver code
let a = new Array ( 65 ) ; a . fill ( 0 ) ; function Count ( i ) { if ( i == 0 ) return 1 ; else if ( i < 0 ) return 0 ; if ( a [ i ] == 0 ) { a [ i ] = ( i + 1 ) + 2 * Count ( i - 1 ) ; return a [ i ] ; } else return a [ i ] ; } function solve ( n ) { let i , sum = 0 ; while ( n > 0 ) { i = parseInt ( Math . log ( n ) / Math . log ( 2 ) , 10 ) ; n = n - parseInt ( Math . pow ( 2 , i ) , 10 ) ; sum = sum + ( i + 1 ) + Count ( i - 1 ) ; } return sum ; } let n = 7 ; document . write ( solve ( n ) ) ;