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: 220
💡 Note: Binary: 1→"1", 2→"10", 3→"11", 4→"100". Concatenated: "1101110" = 128+64+8+4+2 = 220

Constraints

  • 1 ≤ n ≤ 105

Visualization

Tap to expand
Concatenation of Consecutive Binary NumbersInput: n = 3n = 3Binary Representations1→"1"2→"10"3→"11"Concatenated Binary String"11011"Convert to Decimal27
Understanding the Visualization
1
Input
Integer n = 3
2
Process
Convert 1,2,3 to binary and concatenate
3
Output
Decimal value of concatenated binary string
Key Takeaway
🎯 Key Insight: Use bit shifting to avoid string operations and efficiently build the decimal result
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