Given a number
N
, return a string consisting of"0"
s and"1"
s that represents its value in base-2
(negative two).The returned string must have no leading zeroes, unless the string is
"0"
.
Example 1:
Input: 2 Output: "110" Explantion: (-2) ^ 2 + (-2) ^ 1 = 2Example 2:
Input: 3 Output: "111" Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3Example 3:
Input: 4 Output: "100" Explantion: (-2) ^ 2 = 4
Note:
0 <= N <= 10^9
简要解释:
假设一个-2进制的数记为:x(i) x(i-1) x(i-2) ... x(2) x(1)
那么:N = x(i) * (-2)^i + x(i-1)*(-2)^(i-1) + ...+ x(0)(-2)^0
= -2*[x(i) * (-2)^(i-1) + x(i-1)*(-2)^(i-2) + ...+ x(1)*(-2)^1] + x(0)
= -2*X + x(0);
所以,通过判断N的奇偶性,可断定最低位(即x0)是0还是1,然后将N减去最低位的值,进而可求的次低位的值,最终可得整个-2进制的表示。
public String baseNeg2(int N) {
if (N == 0) return "0";
StringBuilder ans = new StringBuilder();
while (N != 0) {
if (N % 2 == 0) {
ans.append(N % 2);
} else {
ans.append("1");
N--;
}
N /= -2;
}
return ans.reverse().toString();
}