Question: how to modify this add function to correctly add pos and negatives, not just positives: BigInteger BigInteger::add ( const BigInteger& N ) const { /

how to modify this add function to correctly add pos and negatives, not just positives: BigInteger BigInteger::add(const BigInteger& N) const {
// Initialize variables to hold the result and carry
BigInteger result;
int carry =0;
// Create copies of the List objects to avoid modifying the originals
List thisDigits = digits;
List NDigits = N.digits;
// Initialize cursors for both BigIntegers
thisDigits.moveBack(); // Move to the back to start from the end
NDigits.moveBack();
// Determine the sign of the result
int resultSign = signum;
// Iterate through the digits of both BigIntegers
while (thisDigits.position()!=0|| NDigits.position()!=0|| carry !=0){
// Calculate the sum of digits plus carry
int sum = carry;
if (thisDigits.position()!=0){
sum += thisDigits.peekPrev();
thisDigits.movePrev();
}
if (NDigits.position()!=0){
sum += NDigits.peekPrev();
NDigits.movePrev();
}
// Handle the case when the result sign chang
if (resultSign ==0){
resultSign =(sum <0)?-1 : 1;
}
// Update carry and prepend the sum digit to the result
carry = sum / base;
result.digits.insertAfter(sum % base);
}
// Set the sign of the result
result.signum = resultSign;
return result;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!