Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find concatenation of consecutive binary numbers in Python
When working with binary representations, we often need to concatenate binary strings of consecutive numbers. This problem asks us to find the decimal value of a binary string formed by concatenating binary representations of numbers from 1 to n.
So, if the input is like n = 4, then the output will be 220 because concatenating binary representations from 1 to 4 gives us "1" + "10" + "11" + "100" = "1101111100", which equals 220 in decimal.
Algorithm Steps
To solve this problem, we follow these steps ?
- Initialize ans := 1 (binary representation of 1)
- Set m := 10^9+7 (modulo value)
- For each number i from 2 to n:
- Left shift ans by the bit length of i
- Add i to ans and take modulo m
- Return the final answer
Implementation
def solve(n):
ans = 1
m = (10**9 + 7)
for i in range(2, n + 1):
# Left shift ans by bit length of current number
ans = ans << i.bit_length()
# Add current number and apply modulo
ans = (ans + i) % m
return ans
# Test with example
n = 4
result = solve(n)
print(f"Input: {n}")
print(f"Output: {result}")
Input: 4 Output: 220
How It Works
Let's trace through the example step by step:
def solve_with_trace(n):
ans = 1
m = (10**9 + 7)
print(f"Initial: ans = {ans} (binary: {bin(ans)})")
for i in range(2, n + 1):
bit_len = i.bit_length()
print(f"\nNumber {i} (binary: {bin(i)}) has bit length: {bit_len}")
ans = ans << bit_len
print(f"After left shift: ans = {ans} (binary: {bin(ans)})")
ans = (ans + i) % m
print(f"After adding {i}: ans = {ans} (binary: {bin(ans)})")
return ans
# Trace the example
result = solve_with_trace(4)
print(f"\nFinal concatenated binary string represents: {result}")
Initial: ans = 1 (binary: 0b1) Number 2 (binary: 0b10) has bit length: 2 After left shift: ans = 4 (binary: 0b100) After adding 2: ans = 6 (binary: 0b110) Number 3 (binary: 0b11) has bit length: 2 After left shift: ans = 24 (binary: 0b11000) After adding 3: ans = 27 (binary: 0b11011) Number 4 (binary: 0b100) has bit length: 3 After left shift: ans = 216 (binary: 0b11011000) After adding 4: ans = 220 (binary: 0b11011100) Final concatenated binary string represents: 220
Testing with Different Values
def solve(n):
ans = 1
m = (10**9 + 7)
for i in range(2, n + 1):
ans = ans << i.bit_length()
ans = (ans + i) % m
return ans
# Test with multiple values
test_cases = [1, 2, 3, 4, 5]
for n in test_cases:
result = solve(n)
print(f"n = {n}: {result}")
n = 1: 1 n = 2: 6 n = 3: 27 n = 4: 220 n = 5: 1765
Conclusion
This algorithm efficiently concatenates binary representations by using bit shifting operations. The key insight is that left shifting by the bit length of a number makes space for concatenation, then adding the number completes the process.
---