Answered step by step
Verified Expert Solution
Question
1 Approved Answer
how do i modify my code so that when adding negative numbers, it actually subtracts them. Here is my add function: BigInteger BigInteger::add ( const
how do i modify my code so that when adding negative numbers, it actually subtracts them. Here is my add function:
BigInteger BigInteger::addconst BigInteger& N const
Initializing variables to store the result and carry
BigInteger result;
int carry ;
Create copies of the List objects to avoid modifying the originals
List thisDigits digits;
List NDigits Ndigits;
Initialize cursors for both BigIntegers
thisDigits.moveBack;
NDigits.moveBack;
Scroll through the digits of the two BigInteger numbers one by one
while thisDigitsposition NDigits.position carry
Calculating sum of digits plus carry
int sum carry;
if thisDigitsposition
sum thisDigits.movePrev;
Check if the current digit of N is negative
if NDigitsposition && Nsignum
sum NDigits.movePrev; Subtract the absolute value
else if NDigitsposition
sum NDigits.movePrev;
Update the carry for the next iteration
carry sum base; Calculate the new carry based on the current sum
sum base; Ensure that sum is within the base range
Add the total to the result
result.digits.insertBeforesum;
Check if the sum is zero
if resultdigits.length && result.digits.front
result.makeZero;
return result;
Set the sign of the result based on the signs of the operands
if signum Nsignum
If signs are the same, result has the same sign
result.signum signum;
else
If signs are different
int comparison compareN;
if comparison
If magnitudes are equal, result is zero
result.makeZero;
return result; Return zero result immediately
else if comparison
If this has greater magnitude, result is positive
result.signum signum;
else
If N has greater magnitude, result is negative
result.signum Nsignum;
return result;
here is some pseudocide that could help, though Im having trouble following it:
Function addN:
Initialize result
Initialize carry
Initialize cursors for both operands
Initialize cursors for this and N
Iterate through digits until both operands are processed
While this or N or carry is not zero:
Initialize sum as carry
Add digits from this operand
If this digit is not zero:
Add this digit to sum
If the current digit of N is negative, treat it as subtraction
If N signum is negative:
Subtract the absolute value of N digit from sum
Else:
Add N digit to sum
Update carry
Set carry based on sum
Add the total to the result
Add sum mod base to result
Set the sign of the result based on the signs of the operands
Set result sign based on the signs of this and N
Return result
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started