Adding Two Negabinary Numbers

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 the array, the 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.

Example:

Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1]
Output: [1,0,0,0,0]
Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<intaddNegabinary(vector<int&arr1vector<int&arr2)
{
    vector<intres;
    reverse(arr1.begin(), arr1.end());
    reverse(arr2.begin(), arr2.end());
    int n = arr1.size(), m = arr2.size();
    int i = n - 1j = m - 1;
    int len = max(nm);
    int carry = 0;
    for (int i = 0i < len + 2i++)
    {
        int x = i < arr1.size() ? arr1[i] : 0;
        int y = i < arr2.size() ? arr2[i] : 0;
        int sum = x + y + carry;
        int r = sum % (-2);
        carry = sum / (-2);
        if (r < 0)
        {
            carry++;
            r += abs(-2);
        }

        res.push_back(r);
    }
    while (res.size() > 1 && res.back() == 0)
    {
        res.pop_back();
    }
    reverse(res.begin(), res.end());
    return res;
}

int main()
{
    vector<intarr1 = {11111};
    vector<intarr2 = {101};

    vector<intres = addNegabinary(arr1arr2);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
        {
            cout << ", ";
        }
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment