To convert a number to base -2, we repeatedly divide the number by -2 and record the remainders. Since the base is negative, we need to ensure the remainder is always non-negative (0 or 1 for binary). If the remainder is negative, we adjust both the quotient and remainder accordingly.
classSolution {
public: string baseNeg2(int n) {
if (n ==0) return"0";
string ans;
while (n !=0) {
int r = n %-2;
n /=-2;
if (r <0) {
r +=2;
n +=1;
}
ans.push_back(r +'0');
}
reverse(ans.begin(), ans.end());
return ans;
}
};
classSolution {
public String baseNeg2(int n) {
if (n == 0) return"0";
StringBuilder ans =new StringBuilder();
while (n != 0) {
int r = n %-2;
n /=-2;
if (r < 0) {
r += 2;
n += 1;
}
ans.append(r);
}
return ans.reverse().toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funbaseNeg2(n: Int): String {
if (n ==0) return"0"var x = n
val ans = StringBuilder()
while (x !=0) {
var r = x % -2 x /= -2if (r < 0) {
r +=2 x +=1 }
ans.append(r)
}
return ans.reverse().toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defbaseNeg2(self, n: int) -> str:
if n ==0:
return"0" ans = []
while n !=0:
r = n %-2 n //=-2if r <0:
r +=2 n +=1 ans.append(str(r))
return''.join(ans[::-1])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnbase_neg2(mut n: i32) -> String {
if n ==0 {
return"0".to_string();
}
letmut ans = Vec::new();
while n !=0 {
letmut r = n %-2;
n /=-2;
if r <0 {
r +=2;
n +=1;
}
ans.push((r asu8+b'0') aschar);
}
ans.iter().rev().collect()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
baseNeg2(n: number):string {
if (n===0) return"0";
letans='';
while (n!==0) {
letr=n%-2;
n= Math.floor(n/-2);
if (r<0) {
r+=2;
n+=1;
}
ans=r.toString() +ans;
}
returnans;
}
}