LC.P1017[负二进制转换]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public String baseNeg2(int n) {
if (n == 0) return "0";
StringBuilder builder = new StringBuilder();
while (n != 0) {
int remainder = n % (-2);
n /= -2;
if (remainder < 0) {
remainder += 2;
++n;
}
builder.append(remainder);
}
return builder.reverse().toString();
}
}
  • 时间复杂度:$O(logn)$
  • 空间复杂度:$O(1)$