Is there a way to add positives and negatives with the same algorithm?

68 Views Asked by At

It is taught to us in grade school that you can add (positive) numbers like this:

    5 2 3
    4 5 6
   -------
    5 7 9

But if we change it to 523 + (-456), we cannot use the same algorithm

    5  2  3
   -4 -5 -6  
   ---------
    1 -3 -3 

I know that I can evaluate that to 100 + -(30) + (-3) which gets 67, but in my situation, 17 is the maximum integer, and -17 is the minimum integer (excluding the actual numbers being added). Is there a way to do this where the 523 + 456 also works?

1

There are 1 best solutions below

2
On BEST ANSWER

The reason why long long data type in c++ represents numbers range from $\ -2^{63}\ $ to $\ 2^{63}-1\ $ is because the representation used is $64$-bit twos complement. An analogous representations in decimal would be $n$-digit "tens complement", for some $\ n\ $, which could represent all the numbers in the range $\ -\frac{10^n}{2}\ $ to $\ \frac{10^n}{2}-1\ $, so it's not at all clear (not, at lest, to me) where your "maximum integer" of $17$ comes from, or what it is meant to be the maximum of.

Nevertheless, if you represent decimal numbers using sequences of positive and negative digits from $-9$ to $9$, as you have done, you can convert any representation to any equivalent one without needing to use any numbers outside the range $-9$ to $9$.

In your example, $\ 1\ -3\ -3\ $, for instance, first replace the rightmost digit by $7$ and decrease the next digit to the left by $1$ to get the equivalent representation $\ 1\ -4\ \ 7\ $. You don't even need to get the $7$ by subtracting $3$ from $10$, since you can get it by subtracting one less than $3$, namely $2$, from $9$.

Next, replace the new middle digit, $-4$, with $6$, and decrease the leftmost digit by $1$ to get the equivalent representation $\ 0\ 6\ 7\ $, from which the new leftmost digit $0$ can be deleted to give you $67$.