1017. Convert to Base -2
Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2Input: 3
Output: "111"
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3Input: 4
Output: "100"
Explantion: (-2) ^ 2 = 4string baseNeg2(int N) {
string res;
while (N) {
cout << "N: " << N << endl;
res = to_string(N & 1) + res;
// -x = ~x + 1
N = -(N >> 1);
}
return res.empty() ? "0" : res;
}Last updated