Question

So for a BigInt problem, I want to add an operator-, how would I change my code for that? It's just for practice, but I'm having some problem finding the solution for change.

Here is my operator+:

int carry = 0;
    int sum;
    BigInt result;
    list<int>::reverse_iterator rit1 = number.rbegin();
    list<int>::reverse_iterator rit2 = operand.number.rbegin();
    while ( (rit1 != number.rend()) || (rit2 != operand.number.rend()) )
    {
        sum = 0;

        if (rit1 != number.rend())
        {
            sum += *rit1;
            rit1++;
        }

        if (rit2 != operand.number.rend())
        {
            sum += *rit2;
            rit2++;
        }

        sum += carry;
        result.number.push_front(sum % 10);
        carry = sum / 10;
    }

    if (carry > 0)
        result.number.push_front(carry);

    return result;
Was it helpful?

Solution

Why not build operator- in terms of x + -y...? If you don't have a negation operator yet, seems good to add, and easier. Then you'll need to fix your operator+ to handle negative numbers, but it's not much use to anyone if it can't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top