Skip to main content
Back to problems
#1073
Medium Algorithms

Adding two negabinary numbers

Array Math
37.6% acceptance
Feb 25, 2026
337
130
Given two numbers arr1 and arr2 in base -2, return the result of adding them together. Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn add_negabinary(arr1: Vec<i32>, arr2: Vec<i32>) -> Vec<i32> {
    let (mut i1, mut i2) = (arr1.len() as i32 - 1, arr2.len() as i32 - 1);
    let mut carry = 0i32;
    let mut res = vec![];
    while i1 >= 0 || i2 >= 0 || carry != 0 {
      let mut sum = carry;
      if i1 >= 0 { sum += arr1[i1 as usize]; i1 -= 1; }
      if i2 >= 0 { sum += arr2[i2 as usize]; i2 -= 1; }
      let bit = ((sum % 2) + 2) % 2;
      carry = -((sum - bit) / 2);
      res.push(bit);
    }
    while res.len() > 1 && *res.last().unwrap() == 0 { res.pop(); }
    res.reverse();
    res
  }
}