LeetCode Solutions

1017. Convert to Base -2

Time:

Space:

			

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

    while (N) {
      ans = to_string(N & 1) + ans;
      N = -(N >> 1);
    }

    return ans == "" ? "0" : ans;
  }
};
			

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

    while (N != 0) {
      sb.append(N & 1);
      N = -(N >> 1);
    }

    return sb.length() > 0 ? sb.reverse().toString() : "0";
  }
}
			

class Solution:
  def baseNeg2(self, N: int) -> str:
    ans = ''

    while N:
      ans = str(N & 1) + ans
      N = -(N >> 1)

    return '0' if ans == '' else ans