Concatenation of Consecutive Binary Numbers - Problem
You're given an integer n, and your task is to create a binary concatenation sequence. Here's how it works:
- Convert each number from
1toninto its binary representation - Concatenate all these binary strings together in order
- Convert the final concatenated binary string back to decimal
- Return the result modulo
109 + 7
Example: For n = 3:
- 1 in binary:
"1" - 2 in binary:
"10" - 3 in binary:
"11" - Concatenated:
"11011" - Decimal value:
27
The challenge lies in handling large values of n efficiently, as the concatenated binary string can become extremely long. You'll need to use bit manipulation techniques to avoid actually building the string!
Input & Output
example_1.py โ Basic Case
$
Input:
n = 1
โบ
Output:
1
๐ก Note:
Only number 1, binary is '1', decimal value is 1
example_2.py โ Small Sequence
$
Input:
n = 3
โบ
Output:
27
๐ก Note:
1โ'1', 2โ'10', 3โ'11'. Concatenated: '11011' = 16+8+2+1 = 27
example_3.py โ Larger Case
$
Input:
n = 12
โบ
Output:
505379714
๐ก Note:
Binary sequence: '1101110010110111000100110101111110011011' converted to decimal and taken modulo 10^9+7
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Chain
Start with empty result = 0
2
Add Number 1
1 has 1 bit, result becomes 1
3
Add Number 2
2 has 2 bits, shift result left 2 positions, add 2: result = 6
4
Add Number 3
3 has 2 bits, shift result left 2 positions, add 3: result = 27
5
Continue Pattern
Keep shifting and adding for all numbers up to n
Key Takeaway
๐ฏ Key Insight: Use bit shifting `(result << bits) + number` instead of string concatenation to achieve O(n) time and O(1) space complexity while handling modular arithmetic efficiently.
Time & Space Complexity
Time Complexity
O(n)
Single loop through numbers 1 to n, with O(1) operations per iteration
โ Linear Growth
Space Complexity
O(1)
Only uses a constant amount of extra space for variables
โ Linear Space
Constraints
- 1 โค n โค 105
- Result must be returned modulo 109 + 7
- The concatenated binary string can be extremely long
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code