LongInt LongInt::operator-( const LongInt &rhs ) const { LongInt result; if(negative == rhs.negative) { if ((*this) <= rhs && !negative) { LongInt subtrahend(rhs); subtrahend.convertSign(); subtrahend.negative = 0; result = (*this)+subtrahend; result.negative = 1; } else if ((*this) > rhs && !negative) { LongInt minuend((*this)); minuend.convertSign(); minuend.negative = 0; result = minuend+rhs; result.negative = 1; result.convertSign(); } else if ((*this) <= rhs && negative) { LongInt minuend((*this)); minuend.negative = 0; LongInt subtrahend(rhs); subtrahend.convertSign(); result = minuend+subtrahend; result.negative = 1; } else { LongInt minuend((*this)); minuend.convertSign(); LongInt subtrahend(rhs); subtrahend.negative = 0; result = minuend+subtrahend; result.negative = 1; result.convertSign(); } result.remove0s(); } else { if (negative && !rhs.negative){ LongInt temp(rhs); temp.convertSign(); result = (*this) + (temp); } if (!negative && rhs.negative) { LongInt temp(rhs); temp.convertSign(); result = (*this) +(temp); } } return result; }
// Arithmetic binary operators LongInt LongInt::operator+( const LongInt &rhs ) const { LongInt result; if(negative == rhs.negative) { if (negative) { LongInt left(*this); LongInt right(rhs); left.convertSign(); right.convertSign(); result = left + right; result.convertSign(); return result; } Deque<char> r(rhs.digits); //right side Deque<char> l(digits); //left side int i = 0; int carry = 0; while (i < max(r.size(), l.size())) { int sum; int lval; int rval; (!l.isEmpty()) ? lval = (int)l.removeBack() - 48 : lval = 0; (!r.isEmpty()) ? rval = (int)r.removeBack() - 48 : rval = 0; sum = lval + rval + carry; carry = sum / 10; result.digits.addFront((char)(sum % 10 + 48)); } if (carry) result.digits.addFront('1'); } else { if (rhs.negative) { // this positive rhs negative LongInt temp(rhs); temp.convertSign(); result = operator-(temp); } else { // this negative rhs positive LongInt temp((*this)); temp.convertSign(); result = rhs.operator-(temp); } } return result; }