The Concatenation of Consecutive Binary Numbers coding problem asks you to take all integers from 1 to n, convert them to their binary string representations, and concatenate these strings in order. You then need to return the decimal value of the resulting large binary string, modulo 10^9 + 7. For example, if n=3, the binary strings are "1", "10", and "11". Concatenated, they form "11011", which is 27 in decimal.
Amazon uses this Bit Manipulation interview pattern to test your ability to work with bitwise operations and large numbers. It evaluates if you can identify a mathematical way to "shift" and "add" numbers without actually converting them to strings, which would be extremely slow and memory-intensive.
The problem is solved using Iterative Bit Shifting and Modular Arithmetic.
For each number i from 1 to n:
i. Let's call it len.len bits: res = res << len.i to the result: res = (res + i) % modulo.
The key is to update the "shift length" only when i reaches a new power of 2.n = 3
1 (1 bit). Result = 1.10 (2 bits).
100 (binary) = 4 (decimal).4 + 2 = 6. (Binary 110).11 (2 bits).
11000 (binary) = 24 (decimal).24 + 3 = 27. (Binary 11011).
Result: 27.n.i using log2 in every loop, which can be slow and prone to precision errors. A simple bit check is better.Practice using (i & (i - 1)) == 0 to detect when a number is a power of 2. This is a very common trick in bit manipulation problems to know when you need to increment your "bit length" counter.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the K-th Character in String Game I | Easy | Solve | |
| Add Binary | Easy | Solve | |
| Find Three Consecutive Integers That Sum to a Given Number | Medium | Solve | |
| Water Bottles II | Medium | Solve | |
| Sum of Two Integers | Medium | Solve |