Problem 1680

Abstract / Summary

Given a number n, create a string by joining the binary forms of numbers from 1 to n and return its decimal value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1680.py

class Solution:
    def concatenatedBinary(self, n: int) -> int:
        result = 0
        shift  = 0
        for i in range(1, n+1):
            # exactly one bit set => bit representation just got longer
            if i & (i-1) == 0:
                shift += 1

            result <<= shift
            result  += i
            # avoiding large numbers which slow down the program
            result  %= 10**9 + 7

        return result
15 lines | 454 bytes | submitted September 23, 2023 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (200k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Math
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the integer formed by concatenating the binary representations of all numbers from 1 to n, then returns the result modulo 10⁹ + 7. The algorithm proceeds in a single forward pass, maintaining a running value that is progressively shifted and extended with each successive integer. By updating the shift width only when the binary length of the current integer increases, the code avoids recomputing the bit-length repeatedly. A modular reduction after each iteration prevents the intermediate value from growing beyond the range of native integer arithmetic, which keeps the execution fast even for large inputs.

Key Steps

Detecting a change in binary length

The binary length of a positive integer grows exactly when the integer is a power of two. The code uses a classic bit-wise test to identify such numbers:

if i & (i-1) == 0:
    shift += 1

When i has only a single set bit, the expression i & (i-1) evaluates to zero, signalling that the next integer will require one more bit in its binary representation. The variable shift therefore tracks the current width of the binary block that must be appended.

Shifting the accumulated result

Before appending the new integer, the accumulated result is left-shifted by the current shift value:

result <<= shift

A left shift by k positions is equivalent to multiplying by 2ᵏ, which aligns the existing bits to make room for the next binary block. Because shift is updated only when the binary length changes, the shift amount is always the exact number of bits needed for the new integer.

Adding the current integer

After creating space, the current integer i is added directly to the shifted result:

result += i

Since i already occupies exactly shift bits, this operation effectively concatenates its binary representation onto the tail of the accumulated binary string.

Applying the modular reduction

To keep the intermediate value within a manageable range, the code reduces the result modulo the prime 10**9 + 7 after each iteration:

result %= 10**9 + 7

This step prevents the integer from expanding to an unwieldy size, which would otherwise slow down arithmetic operations due to Python’s arbitrary-precision integers. By performing the reduction at every step, the algorithm ensures that each intermediate value stays bounded, leading to consistent performance.

Returning the final value

When the loop finishes, the variable result already contains the required concatenated binary number reduced modulo the given constant, and it is returned directly:

return result

Edge Cases Handled

When n is zero, the for loop does not execute because the range 1 to n+1 is empty. Consequently, result remains at its initial value of 0, and the function returns 0. This behavior correctly represents the concatenation of an empty sequence of binary numbers.

The power-of-two detection works for the smallest power, 1, because 1 & 0 equals 0. The shift variable is therefore incremented from its initial value of 0 to 1 before the first concatenation, ensuring that the first binary digit is placed correctly.

Because the modular reduction is applied after each addition, the function safely handles the maximum possible intermediate value that could arise from concatenating up to the largest supported n. The reduction guarantees that overflow never occurs, even when the concatenated binary string would otherwise exceed the limits of typical fixed-size integer types.

Performance Optimizations

The algorithm avoids recomputing the bit length of each integer by maintaining a running shift counter that only changes when a power of two is encountered. This eliminates the need for costly logarithmic or string-based length calculations.

Using the left-shift operator (<<=) to create space for the new bits is more efficient than multiplying by a power of two, as the operation maps directly to low-level bit manipulation instructions.

The modular reduction is performed inside the loop rather than only at the end. By keeping the intermediate result bounded, the code prevents Python’s arbitrary-precision integer implementation from allocating increasingly larger memory blocks, which would degrade speed for large n. This incremental reduction thus preserves a tight execution profile throughout the entire iteration.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a little robot that loves to collect numbers. This robot wants to build a giant string of special numbers made of only zeros and ones. Think of this like building a long tower out of blocks. The code starts with an empty space and gets ready to stack numbers one by one, from one up to the number that was chosen.

Every time the robot goes to pick up the next number, it checks if the number is a special power of two. When that happens, the length of the binary string gets a little bit longer, so the robot makes sure to remember that extra space.

Then, the robot takes the long chain of numbers it has built so far and pushes everything over to the left to make room for the new number. This is like sliding your toys to the side so you can put a new toy on your shelf. Once the shelf has space, the new number is added to the end.

Because the building can get super tall and messy if the numbers grow too big, the robot performs a trick to keep the number manageable by dividing it and keeping only the remainder. This keeps the tower tidy while the robot finishes adding every number in the line. After all the numbers have been added and sorted into the right spot, the big chain is complete.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.74 | σ = 1.32

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS Go C# Rust TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
withaarzoo C++
YuriSpiridonov Python
32 links | 18 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

21 solutions   September 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality