LeetCode 1017: Convert to Base -2 Solution

Master LeetCode problem 1017 (Convert to Base -2), 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.

1017. Convert to Base -2

Medium

Problem Explanation

Explanation

To convert a number to base -2, we can use the idea of binary representation. We can repeatedly divide the number by -2 and keep track of the remainder. The remainder will be either 0 or 1. If the remainder is negative, we need to add 2 to it and update the number as well. This process continues until the number becomes 0. Then, the remainders in reverse order will give us the base -2 representation of the number.

  • Time complexity: O(log n) where n is the input number
  • Space complexity: O(log n) to store the remainders

Solution Code

class Solution {
    public String baseNeg2(int n) {
        if (n == 0) return "0";
        
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            int remainder = n % -2;
            n /= -2;
            if (remainder < 0) {
                remainder += 2;
                n += 1;
            }
            sb.append(remainder);
        }
        
        return sb.reverse().toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1017 (Convert to Base -2)?

This page provides optimized solutions for LeetCode problem 1017 (Convert to Base -2) 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 1017 (Convert to Base -2)?

The time complexity for LeetCode 1017 (Convert to Base -2) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1017 on DevExCode?

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

Back to LeetCode Solutions