Is there a way to add positives and negatives with the same algorithm where the |negative number| is greater?

45 Views Asked by At

I recently asked this question on adding positives and negatives using the same algorithm. The accept answer works amazingly, until I tried where the absolute value of the negative number is larger. When I used the same steps, I got this:

  7  6  7  6
 -8 -7 -8 -7
-------------
 -1 -1 -1 -1
 -2 -2 -2  9
  8  8  8  9

Now here, 8889 is obviously the wrong answer (as the real answer was in fact -1111), and in my code, I cannot see the two numbers being added (i.e. 7676 and -8787) after I add them (thus I only have an array [-1, -1, -1, -1] to work with). Is there a way to account for this (again not surpassing 18 (I made a mistake last time) and not go below -18) or am I doing something wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

You need a "reserve". When you "borrow" you take one faith that there well be positive well at the end.

When you do the $-1\to 9$ you are borrowing $10$ and when you do the $-2\ 9 \to 8\ 9$ you are borrowing $100$ and so on.

And the final case when you get $8889$ you are borrowing $10000$ that.... just isn't there at all. So we have to do $8889 -10000 = -1111$. But thats an extra branch and takes us back to where we started.

But why go right to left rather than left to right? The reason we teach left to right to children is that in has the advantage we only have to keep one tally and "borrowing" or "carrying" won't require as second tally to keep track of. But note: we deal with the minutia first.

If we go right to left we deal with the highest powers of $10$ first and that's what's going to dominate the entire number.

If we go right to left and our first term is negative... well then then entire term is going to be negative, and if it is positive the entire term will be positive. Then we borrow and carry only when you change signs; making them all negative if the first term was, or all positive if the first term was.

So having $-1\ -1 \ -1 \ -1\to -1111$ is the corect answer.

Let's do a more complex issue $3649 +(-5493)$ will give us

 3  6  4  9
-5 -4 -9 -3
-----------
-2  2 -5  6
-1 -8 -5  6
-1 -8 -4 -4

So $3649 + (-5493) = -1844$

And were we to have the other way $ (-3649)+5493$ where the positive is higher it works the same way.

-3 -6 -4 -9
 5  4  9  3
-----------
 2 -2  5 -6
 1  8  5 -6
 1  8  4  4

And $ (-3649)+5493=1844$

0
On

The problem is that you have no way of representing negative numbers. With four digits, you have $10,000$ possible values. There are $19,999$ numbers from $-9999$ to $9999$, so something's got to give. If the first non-zero number in your array is negative, then you know the answer should really be negative. Then it's the answer you got, minus $10000$: $$8889-10000=-1111$$ This won't allow you to add and subtract negative numbers, just to detect an overflow when you subtract.