Skip to content

1017. Convert to Base -2

  • Time: $O(\log n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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()};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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";
  }
}
1
2
3
4
5
6
7
8
9
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'