在链表c ++中减去二进制数

时间:2014-09-27 01:00:15

标签: c++

你好新发帖但很长时间的追随者。我一直在研究一个项目很长一段时间,我不能为我的生活找出如何在链表中实现两个二进制数的减法运算符。程序将采用整数并将其转换为二进制,然后对二进制数进行加,减和乘,然后返回结果。

所以我已经完成了加法运算符,(这很好,只是想表明我是如何做我的主要cpp。)

除了

Binary operator+(const Binary &b1, const Binary &b2){
Binary newBinary = Binary();
unsigned iMax = b1.get_degree();
if (iMax < b2.get_degree()){
    iMax = b2.get_degree();
}
//carry bit
unsigned bCarry = 0;
//traverse the list for each bit b1 and b2, highest degree
for (unsigned i = 0; i <= iMax; ++i){
    unsigned sum = b1.get_bit(i) + b2.get_bit(i) + bCarry;

    //determine if there is new carry
    if (sum >= 2){
        bCarry = 1;
        sum -= 2;
    }
    else bCarry = 0;
    if (1 == sum){
        newBinary.set_bit(1, i);
    }
}
//handle extra carry bit    
if (1 == bCarry){
    newBinary.set_bit(1, iMax + 1);
    return newBinary;
}

}

添加工作正常,我试图采取添加做什么并将其应用于减法运算符,但我继续击中墙lol

减法:

Binary operator-(const Binary &b1, const Binary &b2){
Binary newBinary = Binary();
unsigned iMax = b1.get_degree();
Binary switchNode = Binary();
int cutoffBit = b1.get_degree();

if (iMax < b2.get_degree()){
    iMax = b2.get_degree();
}

//swtich the bits of b2 by switching them from 0 to 1 and from 1 to 0
//then add 1 to b2
for (unsigned i = 0; i < cutoffBit; i++){
    if (b2.get_bit(i) == 0){
        switchNode.set_bit(1, i);
    }
    else if (b2.get_bit(i) == 1){
        switchNode.set_bit(0, i-1);
    }
} 

cout << switchNode; cout << "\t switchNode";
cout << "\n";
cout << b2; cout<< "\t b2";

unsigned bCarry = 0;
//sub the two binary numbers.
for (unsigned i = 0; i <= iMax; ++i){
    unsigned sub = b1.get_bit(i) + b2.get_bit(i);

    if (sub >= 0){
        bCarry = 0;
        sub -= 1;
    }
    else bCarry = 1;
    if (1 == sub){
        switchNode.set_bit(1, i);
    }
}
//handles the drop bit
if (1 == bCarry){
    switchNode.set_bit(1, iMax - 1);
    return switchNode - 1;
}
cout << "\n";
cout << switchNode; cout << "\t switch node";

我试图用我的couts做一些调试,以便那些为什么那里..所以任何帮助指向我正确的方向将非常感谢!

-Jason

1 个答案:

答案 0 :(得分:0)

你的2的补码(“翻转位并加1”)似乎没有做它声称做的事情。例如,如果位0为1,它将尝试设置位-1!