Leetcode 1073: Adding Two Negabinary Numbers

grid47
grid47
Exploring patterns and algorithms
Jul 22, 2024 7 min read

You are given two numbers represented in base -2. Each number is given as an array of binary digits (0s and 1s), where the most significant bit is at the beginning of the array. Your task is to add these two numbers together and return the result in the same format, as an array of 0s and 1s in base -2, without leading zeros.
Problem
Approach
Steps
Complexity
Input: The input consists of two arrays, arr1 and arr2, each representing a number in base -2. The arrays contain binary digits, where arr1[i] and arr2[i] are either 0 or 1, and there are no leading zeros in either array.
Example: Input: arr1 = [1, 0, 1], arr2 = [1, 1]
Constraints:
• 1 <= arr1.length, arr2.length <= 1000
• arr1[i] and arr2[i] are 0 or 1
• arr1 and arr2 have no leading zeros
Output: The output should be an array of binary digits representing the sum of the two input numbers in base -2, with no leading zeros.
Example: Output: [1, 0, 0, 0]
Constraints:
• The output should be a binary array representing the sum of the numbers in base -2.
Goal: To add two numbers in base -2 and return the result in base -2 format without leading zeros.
Steps:
• 1. Initialize a carry variable to store any carryover during the addition process.
• 2. Traverse both arrays from the least significant bit to the most significant bit.
• 3. Add the corresponding bits from both arrays along with the carry, and store the result in the result array.
• 4. If the sum of bits results in a carry, update the carry variable.
• 5. Continue this process until all bits have been added, and ensure the result array has no leading zeros.
Goal: The input arrays should be of valid lengths and contain binary digits only. The arrays should not contain leading zeros, except when the array represents zero.
Steps:
• 1 <= arr1.length, arr2.length <= 1000
• arr1[i] and arr2[i] are 0 or 1
• arr1 and arr2 have no leading zeros
Assumptions:
• The input arrays represent valid binary numbers in base -2.
• The solution should handle arrays of varying lengths efficiently.
Input: Input: arr1 = [1, 0, 1], arr2 = [1, 1]
Explanation: The number represented by arr1 is 5 and the number represented by arr2 is 3. Their sum is 8, which is represented as [1, 0, 0, 0] in base -2.

Input: Input: arr1 = [1, 0, 1], arr2 = [0]
Explanation: The number represented by arr1 is 5 and arr2 is 0. The sum is 5, represented as [1, 0, 1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus