#1017
Medium Algorithms Convert to base 2
Math
61.8% acceptance
Feb 25, 2026
572
309
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".
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn base_neg2(n: i32) -> String {
if n == 0 { return "0".to_string(); }
let mut n = n;
let mut bits = Vec::new();
while n != 0 {
let rem = n & 1;
bits.push(rem.to_string());
n = -(n >> 1);
}
bits.iter().rev().cloned().collect()
}
}