简体   繁体   中英

Calculate the sum of two positive or negative integers

I am learning python by trying to solve question as follows.

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example: Given a = 1 and b = 2, return 3.

The following solution that I have came up works with positive integers but it does not work if a= -1 and b =1.

I wonder how do you handle negative values.

class Solution(object):
def getSum(self, a, b):
    """
    :type a: int
    :type b: int
    :rtype: int
    """
    while b != 0:
        carry = a&b
        a= a^b
        b= carry<<1
    return a

If you actually want to learn Python, there are many other ways of finding the sum of two numbers. Using bitwise operators only can teach you the algorithms involved, which IMO, is not a good way for starting to learn any language; therefore, my answer will not be involving any bitwise operations .

Here are many ways to add without using the plus ("+") operator with built in Python functionalities:

a = 1
b = 2

# The "sassy" way as suggested by miradulo, uses the built in function `sum()`
print(sum((a, b)))

# uses a's __add__ magic method to add with b 
print(a.__add__(b))

# similar to the previous, but directly uses int's __add__ instead
print(int.__add__(a, b))

# uses the add operator as a function, equivalent to `anything + anything`
from operator import add
print(add(a, b))

# they all return '3'

To solve your approach, you should check what values do not work, and catch them somehow (eg, if a == -1 and b == 1 )

EDIT: As BOi and hotspring pointed out, it only fails when a and b have different signs. You could add a substract function (see the other answer) and use it as Substract(a, -b) if a < 0 xor b < 0.

Another possible approach - being slow, but easy - would probably be the following:

  1. See if second operand is negative.
  2. If it is not (which means, if b is positive ), increment a and decrement b, until b is zero.
  3. If it is (which means, if b is negative ), decrement a and increment b, until b is zero.

I figured it out. A solution without using built in function such as sum() . First you define a function to subtract without the - operator. Then you can use that to solve it. Here you go!:

def getSum(a, b):
    negative_number = None
    if a == 0:
        return b
    elif b == 0:
        return a
    if a < 0 and b < 0:
        pass
    elif a < 0:
        negative_number = a
    elif b < 0:
        negative_number = b
    if (a < 0 and b < 0) and abs(a) == abs(b):
        return int("-%s" % (str(getSum(abs(a), abs(b)))))
    elif abs(a) == abs(b) and (a < 0 or b < 0):
        return 0
    elif negative_number != None:
        x = getSum(abs(a), abs(b))
        if x > 2*abs(negative_number):
            return subtract(getSum(abs(a), abs(b)), 2*abs(negative_number))
        else:
            return subtract(2*abs(negative_number), getSum(abs(a), abs(b)))
    while b != 0:
        carry = a&b
        a = a^b
        b= carry<<1
    return a

def subtract(x, y): #Subtraction function without - operator.
    while (y != 0):
        borrow = (~x) & y
        x = x ^ y
        y = borrow << 1

    return x
print (getSum(-15, 16)) #Substitute -15 and 16 for any values to find the sum

Now try whatever posibilities you want. it should work well for most numbers except for a few corner cases which I will attack and I will post the full solution as soon as I have one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM