Make delicious recipes!

Subtract using plus operator only


Solution: Since a-b = a + (-b),
this problem is easy if we can find negative of a number using only the plus operator.

Here is how to do it:
int negate(int num)
{
    int minusA = 0;
    int decrementUnit = num < 0 ? 1 : -1;  
    while (num != 0)
    {
        minusA += decrementUnit;
        num += decrementUnit;
    }
    return minusA;
}

int subtract (int a, int b)
{
    return a + negate(b);
}
Execution for negate(5)
minusA decrementUnit num
0-15
-1-14
-2-13
-3-12
-4-11
-5-10






Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal