Skip to content
Advertisement

decimal value of the number formed by concatenating the binary representations of first n natural numbers

Given a number n, find the decimal value of the number formed by concatenating the binary representations of first n natural numbers.
Print answer modulo 10^9+7.

Also, n can be as big as 10^9 and hence logarithmic time approach is needed.

Eg: n=4, Answer = 220

Explanation: Number formed=11011100 (1=1,2=10,3=11,4=100). Decimal value of 11011100="220".

The code I am using below only works for first integers N<=15

JavaScript

Advertisement

Answer

Note that working with string representation is not necessary (moreover, is not useful after task changing). Look at approach with bitwise arithmetics (Python, but principle is the same)

With new condition concerning modulo 1000000007 we have just add modulo operation to result calculation line at every step, because shift left and or-ing is equivalent to multiplication by power of two and adding, these operations are obeyed to equivalence relations for modulo properties. Note that intermediate results don’t exceed 1000000007*n, so long type is suitable here for reasonable n values.

JavaScript

variant without bitwise operations:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement