[LeetCode] Convert to Base -2

1017. Convert to Base -2

Given an integer n, return a binary string representing its representation in base -2.

Note that the returned string should not have leading zeros unless the string is “0”.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
string baseNeg2(int n) {
string res = "";
while(n) {
res = to_string(n & 1) + res;
n = -(n>>1);
}
return res == "" ? "0" : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/21/PS/LeetCode/convert-to-base-2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.