LeetCode 1073: Adding Two Negabinary Numbers Solution
Master LeetCode problem 1073 (Adding Two Negabinary Numbers), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To add two negabinary numbers, we can perform the addition similar to binary addition but with some additional rules due to the base being -2. We start by adding digits from the least significant bit (LSB) to the most significant bit (MSB). If the sum of two digits at a position is even, we write 0 in the result. If the sum is odd, we write 1. If the sum is -1, we write 1 and borrow 1 to the next higher bit. If the sum is -2, we write 0 and borrow -1 to the next higher bit. We continue this process until we reach the MSB.
Time Complexity
The time complexity of this algorithm is O(max(n, m)), where n and m are the lengths of the input arrays arr1 and arr2.
Space Complexity
The space complexity of this algorithm is O(max(n, m)), as we are storing the result array of the same length as the longer input array.
Solution Code
class Solution {
public int[] addNegabinary(int[] arr1, int[] arr2) {
int n = arr1.length, m = arr2.length;
int maxLen = Math.max(n, m);
int[] res = new int[maxLen + 2];
int carry = 0, index = maxLen + 1;
for (int i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry != 0; i--, j--) {
if (i >= 0) carry += arr1[i];
if (j >= 0) carry += arr2[j];
res[index--] = Math.abs(carry % 2);
carry = -(carry / 2);
}
int start = index + 1;
while (start < maxLen + 2 && res[start] == 0) start++;
if (start == maxLen + 2) return new int[]{0};
return Arrays.copyOfRange(res, start, maxLen + 2);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1073 (Adding Two Negabinary Numbers)?
This page provides optimized solutions for LeetCode problem 1073 (Adding Two Negabinary Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1073 (Adding Two Negabinary Numbers)?
The time complexity for LeetCode 1073 (Adding Two Negabinary Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1073 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1073 in Java, C++, or Python.