text: Sum of decimals that are binary representations of first N natural numbers | JavaScript program to implement the above approach ; Function to find the sum of first N natural numbers represented in binary representation ; Stores the resultant sum ; Iterate until the value of N is greater than 0 ; If N is less than 2 ; Store the MSB position of N ; Iterate in the range [ 1 , x ] and add the contribution of the numbers from 1 to ( 2 ^ x - 1 ) ; Update the value of the cur and add ; Add the cur to ans ; Store the remaining numbers ; Add the contribution by MSB by the remaining numbers ; The next iteration will be repeated for 2 ^ x - 1 ; Print the result ; Driver code
code: let MOD = 1000000007 ; function sumOfBinaryNumbers ( n ) { let ans = 0 ; let one = 1 ; while ( true ) { if ( n <= 1 ) { ans = ( ans + n ) % MOD ; break ; } let x = Math . floor ( Math . log ( n ) / Math . log ( 2 ) ) ; let cur = 0 ; let add = Math . floor ( Math . pow ( 2 , ( x - 1 ) ) ) ; for ( let i = 1 ; i <= x ; i ++ ) { cur = ( cur + add ) % MOD ; add = ( add * 10 % MOD ) ; } ans = ( ans + cur ) % MOD ; let rem = n - Math . floor ( Math . pow ( 2 , x ) ) + 1 ; let p = Math . floor ( Math . pow ( 10 , x ) ) ; p = ( p * ( rem % MOD ) ) % MOD ; ans = ( ans + p ) % MOD ; n = rem - 1 ; } document . write ( ans ) ; } let N = 3 ; sumOfBinaryNumbers ( N ) ;