Concatenation of Consecutive Binary Numbers - Problem

Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.

For example, if n = 3, the binary representations are:

  • 1"1"
  • 2"10"
  • 3"11"

Concatenating them gives "11011", which is 27 in decimal.

Input & Output

Example 1 — Basic Case
$ Input: n = 1
Output: 1
💡 Note: Only number 1 has binary representation "1", so result is 1 in decimal
Example 2 — Small Range
$ Input: n = 3
Output: 27
💡 Note: Binary: 1→"1", 2→"10", 3→"11". Concatenated: "11011" = 16+8+2+1 = 27
Example 3 — Power of 2
$ Input: n = 4
Output: 110
💡 Note: Binary: 1→"1", 2→"10", 3→"11", 4→"100". Concatenated: "1101110" = 64+32+8+4+2 = 110

Constraints

  • 1 ≤ n ≤ 105

Visualization

Tap to expand
Concatenation of Consecutive Binary Numbers INPUT Given: n = 1 n = 1 Binary Representations: 1 --> 1 Concatenated Binary: "1" Input Value: n = 1 ALGORITHM STEPS 1 Initialize result result = 0, MOD = 10^9+7 2 Loop i = 1 to n Process each number 3 Bit shift left bits = floor(log2(i)) + 1 4 Update result result = (result << bits) + i For i=1: bits = log2(1)+1 = 1 result = (0 << 1) + 1 = 1 Core Formula: result = ((result << bits) + i) % (10^9 + 7) FINAL RESULT Binary String: "1" Binary to Decimal 1 2^0 Calculation: 1 × 2^0 = 1 OUTPUT 1 Status: OK Result matches expected Key Insight: Bit Shifting Optimization: Instead of building actual binary strings, use bit manipulation. For each number i, shift result left by log2(i)+1 bits, then add i. This gives O(n) time complexity. Apply modulo at each step to prevent overflow. TutorialsPoint - Concatenation of Consecutive Binary Numbers | Bit Shifting Optimization
Asked in
Facebook 15 Google 12 Amazon 8
42.5K Views
Medium Frequency
~25 min Avg. Time
786 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen