LeetCode 1680: Concatenation of Consecutive Binary Numbers Solution

Master LeetCode problem 1680 (Concatenation of Consecutive Binary Numbers), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1680. Concatenation of Consecutive Binary Numbers

Problem Explanation

Explanation:

To solve this problem, we need to concatenate the binary representation of numbers from 1 to n and then convert the concatenated binary string back to decimal modulo 10^9 + 7. The key idea is to build the binary representation of each number iteratively while keeping track of the current decimal value after concatenation.

  1. Initialize result to 0.
  2. Iterate from 1 to n:
    • Calculate the number of bits required to represent the current number.
    • Shift the current result to the left by the number of bits required.
    • Add the current number to the result.
    • Take modulo 10^9 + 7 after each step.
  3. Return the final result. :

Solution Code

class Solution {
    public int concatenatedBinary(int n) {
        long result = 0;
        int MOD = 1000000007;
        
        for (int i = 1; i <= n; i++) {
            int numBits = (int)(Math.log(i) / Math.log(2)) + 1;
            result = (result << numBits | i) % MOD;
        }
        
        return (int)result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1680 (Concatenation of Consecutive Binary Numbers)?

This page provides optimized solutions for LeetCode problem 1680 (Concatenation of Consecutive Binary Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1680 (Concatenation of Consecutive Binary Numbers)?

The time complexity for LeetCode 1680 (Concatenation of Consecutive Binary Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1680 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1680 in Java, C++, or Python.

Back to LeetCode Solutions