text: Sum of decimals that are binary representations of first N natural numbers | / Java program for 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: import java . io . * ; import java . lang . * ; class GFG { static final int MOD = 1000000007 ; static void sumOfBinaryNumbers ( int n ) { int ans = 0 ; int one = 1 ; while ( true ) { if ( n <= 1 ) { ans = ( ans + n ) % MOD ; break ; } int x = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) ; int cur = 0 ; int add = ( int ) ( Math . pow ( 2 , ( x - 1 ) ) ) ; for ( int i = 1 ; i <= x ; i ++ ) { cur = ( cur + add ) % MOD ; add = ( add * 10 % MOD ) ; } ans = ( ans + cur ) % MOD ; int rem = n - ( int ) ( Math . pow ( 2 , x ) ) + 1 ; int p = ( int ) Math . pow ( 10 , x ) ; p = ( p * ( rem % MOD ) ) % MOD ; ans = ( ans + p ) % MOD ; n = rem - 1 ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 3 ; sumOfBinaryNumbers ( N ) ; } }