Skip to content

1017. Convert to Base -2

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  string baseNeg2(int N) {
    string ans;

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

    return ans == "" ? "0" : ans;
  }
};
 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 & 1);
      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:
      ans = str(N & 1) + ans
      N = -(N >> 1)

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