1017. Convert to Base -2 LeetCode Solution

In this guide, you will get 1017. Convert to Base -2 LeetCode Solution with the best time and space complexity. The solution to Convert to Base – problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Convert to Base – solution in C++
  4. Convert to Base – solution in Java
  5. Convert to Base – solution in Python
  6. Additional Resources
1017. Convert to Base -2 LeetCode Solution image

Problem Statement of Convert to Base –

Given an integer n, return a binary string representing its representation in base -2.
Note that the returned string should not have leading zeros unless the string is “0”.

Example 1:

Input: n = 2
Output: “110”
Explantion: (-2)2 + (-2)1 = 2

Example 2:

Input: n = 3
Output: “111”
Explantion: (-2)2 + (-2)1 + (-2)0 = 3

Example 3:

Input: n = 4
Output: “100”
Explantion: (-2)2 = 4

Constraints:

0 <= n <= 109

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(\log n)

1017. Convert to Base -2 LeetCode Solution in C++

class Solution {
 public:
  string baseNeg2(int n) {
    string ans;

    while (n != 0) {
      ans += to_string(n % 2);
      n = -(n >> 1);
    }

    return ans.empty() ? "0" : string{ans.rbegin(), ans.rend()};
  }
};
/* code provided by PROGIEZ */

1017. Convert to Base -2 LeetCode Solution in Java

class Solution {
  public String baseNeg2(int n) {
    StringBuilder sb = new StringBuilder();

    while (n != 0) {
      sb.append(n % 2);
      n = -(n >> 1);
    }

    return sb.length() > 0 ? sb.reverse().toString() : "0";
  }
}
// code provided by PROGIEZ

1017. Convert to Base -2 LeetCode Solution in Python

class Solution:
  def baseNeg2(self, n: int) -> str:
    ans = []

    while n != 0:
      ans.append(str(n % 2))
      n = -(n >> 1)

    return ''.join(reversed(ans)) if ans else '0'
# code by PROGIEZ

Additional Resources

See also  454. 4Sum II LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.