0

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
casillas
  • 16,351
  • 19
  • 115
  • 215
  • Can you cheat with what ever python operators, or do you have to use bit operators? – Rohi Apr 22 '18 at 06:47
  • 3
    what's the question ? – Stéphane Apr 22 '18 at 06:47
  • 4
    If you want to be sassy `sum((a, b))`. – miradulo Apr 22 '18 at 06:50
  • @hotspring it works with negative numbers as well. It just doesn't work when a & b have opposite signs –  Apr 22 '18 at 06:51
  • then how could I cope with this situation? – casillas Apr 22 '18 at 06:51
  • @miradulo, this link also handles only positive integers. My solution works with positive integers as well. – casillas Apr 22 '18 at 06:53
  • A fixed bit length is required for making calculations with signed integers. I'm afraid Python does not guarantee it, but don't know for sure about the internals. – VPfB Apr 22 '18 at 06:59
  • @hotspring Given your integer is 32 bits, see [this question](https://stackoverflow.com/questions/38557464/sum-of-two-integers-without-using-operator-in-python). – miradulo Apr 22 '18 at 07:00
  • Does the question *require* bit twiddling? Why not just `return a.__add__(b)` ? – cdarke Apr 22 '18 at 07:07
  • @abccd Err what makes you think that? Because they are both formatted like Leetcode solutions? – miradulo Apr 22 '18 at 07:22
  • @hotspring: Could you please clarify if you have to use bit operations? If not, feel free to accept abccd's answer, or, if this is too "sassy" for you, to accept mine. – caylee Apr 22 '18 at 07:23
  • 2
    Possible duplicate of [Sum of Two Integers without using "+" operator in python](https://stackoverflow.com/questions/38557464/sum-of-two-integers-without-using-operator-in-python); since it actually solves the problem. – Taku Apr 22 '18 at 07:39

2 Answers2

0

To solve your approach, you should check what values do not work, and catch them somehow (e. g., 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.
caylee
  • 921
  • 6
  • 12
  • It does not fail when a and b have different signs. Please look at my answer. –  Apr 22 '18 at 07:06
  • As hotspring pointed out, it seems to be right anyway. Anyhow, it does not fail in other cases for sure (I hope). This bit operations are nothing one should do in higher-level languages – caylee Apr 22 '18 at 07:19
  • @xanoeteux i'm not sure. maybe it didn't help OP or someone decided it didn't help. i dont really know. –  Apr 22 '18 at 07:33
  • I downvoted because this answer is very incomplete. "catch them somehow"? How? What would your implementation look like? Also for the latter approach, how do you intend on incrementing and decrementing without using `+=` or `-=`? – miradulo Apr 22 '18 at 07:47
0

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.

  • How about try `getSum(10, -100)`.. still broken. – miradulo Apr 22 '18 at 07:35
  • @miradulo i don't what to do about that one. Any help? –  Apr 22 '18 at 07:44
  • You could rewrite `a < 0 or b < 0` as `negative_number != None`. But finally, I assume this answer now to be working. Now wait for the OP… – caylee Apr 22 '18 at 07:45
  • Now you're passing two arguments to `abs`. – miradulo Apr 22 '18 at 07:51
  • @miradulo what do you mean? –  Apr 22 '18 at 07:52
  • @BOi A parentheses issue :) – miradulo Apr 22 '18 at 07:53
  • Also now try `getSum(-10, 100)`, doesn't work. Actually now your example case won't work either. – miradulo Apr 22 '18 at 07:55
  • @miradulo yeah that's why i asked you for help. I dont get why OP cant just use + and -. Making all of our lives harder. :) –  Apr 22 '18 at 07:56
  • Im going to keep this answer here as we're almost close to getting a full solution. meanwhile, i'll try to figure it out. @hotspring have a look at this. There are still some corner cases to fix but it mostly works. I will let you know when I have a full solution. Feel free to edit or comment if you find a full solution. Thanks –  Apr 22 '18 at 08:03
  • @BOi This isn't really a code review site though, and this answer doesn't work - I don't see the value in it. Anyhow with Python having an infinite two's complement representation I doubt you're going to get this to work without separating the positive and negative cases entirely. – miradulo Apr 22 '18 at 08:08
  • @miradulo Done.Found a full solution. It should properly now for real :) –  Apr 22 '18 at 15:47
  • @hotspring here is the full solution –  Apr 22 '18 at 15:47
  • @miradulo wow. ur really good at finding errors in code :) I fixed that case as well. –  Apr 23 '18 at 02:41
  • @BOi Why thank you. Now `getSum(1, -1000)` is 999 ;) – miradulo Apr 23 '18 at 02:42
  • @miradulo holy moly. This code is going to take a lot of effort to fix ;) –  Apr 23 '18 at 02:43