负二进制转化和相加

1. 将整数转化为负二进制形式

vector<int> baseNeg2(int n) {
    if(n==0) return {0};
    vector<int> res;
    int cur;
    int back;
    while(n!=0){
        cur = n&1;
        back = abs(cur);
        res.push_back(back);
        n=(n-cur)/(-2);
    }
    reverse(res.begin(),res.end());
    return res;
}
字符串存储
class Solution {
public:
    string baseNeg2(int n) {
	string str;
        int cur;
        string back;
        while(n!=0){
            cur = n&1;
            back = to_string(abs(cur));
            str = back + str;
            n=(n-cur)/(-2);
        }
        return str.empty()?"0":str;
    }
};

2. 负二进制数相加(模拟)

class Solution {
public:
    vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) {
        int i = arr1.size() - 1, j = arr2.size() - 1;
        int carry = 0;
        vector<int> ans;
        while (i >= 0 || j >= 0 || carry) {
            int x = carry; //当前位数值
            if (i >= 0) x += arr1[i];
            if (j >= 0)  x += arr2[j];
            
            if (x >= 2) {//大于2需要进位
                ans.push_back(x - 2);
                carry = -1;//给了一个,这里是相反的
            }
            else if (x >= 0) {//不进位
                ans.push_back(x);
                carry = 0;
            }
            else {//小于0同样也要进位
                ans.push_back(1);
                carry = 1;//借了一个,这里是相反的
            }
            --i;
            --j;
        }
        while (ans.size() > 1 && ans.back() == 0)  ans.pop_back();//取出前导零
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

posted @ 2023-05-18 00:51  失控D大白兔  阅读(19)  评论(0编辑  收藏  举报