Given a number
N
, return a string consisting of"0"
s and"1"
s that represents its value in base-2
(negative two).javaThe returned string must have no leading zeroes, unless the string is
"0"
.app
Example 1:less
Input: 2 Output: "110" Explantion: (-2) ^ 2 + (-2) ^ 1 = 2
Example 2:ui
Input: 3 Output: "111" Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
Example 3:spa
Input: 4 Output: "100" Explantion: (-2) ^ 2 = 4
Note:code
0 <= N <= 10^9
Approach #1: Math. [Java]blog
class Solution { public String baseNeg2(int N) { if (N == 0) return "0"; StringBuilder sb = new StringBuilder(); while (N != 0) { int remainder = N % (-2); N /= -2; if (remainder < 0) { remainder += 2; N += 1; } sb.append(remainder); } return sb.reverse().toString(); } }
Reference:ip
https://en.wikipedia.org/wiki/Negative_base#Calculationrem
https://www.geeksforgeeks.org/convert-number-negative-base-representation/get