2

Here is the original question.

Here is the code for adding two integers using bitwise operations:

def getSum(self, a, b):

    while (a & b):
        x = a & b
        y = a ^ b
        a = x << 1
        b = y

    return a ^ b

Though I know the reason why it goes into an infinite loop while adding a positive and negative integer, I need some help with coming up with the code-fix for this.

0

1 Answer 1

3

I am assuming that you have gone through the logic behind the infinite loop you are getting. logic

Following is the behaviour of your program :

1. Gives correct result when both a and b are positive.

2. Gives correct result when both a and b are negative.

3. Gives correct result when one of them is positive and one of them is negative
   and positive one is smaller than negative one.

4. Gives incorrect result (infinite loop) when one of them is positive and one of 
   them is negative and positive one is bigger than negative one.`

So you will have to handle the fourth case explicitly. You may write a wrapper for it. Also you need one more utility to negate the value of a number i.e. if the number is positive make it negative and vice versa:

# I will leave neagte(x) on you to implement.
# So assume we have  negate() method available.

def getSum(a,b):
     # if a is -ve and b is +ve and abs(a) is less than b.
     cond1 =  a < 0 and b > 0 and abs(a) < b

     # if b is -ve and a is +ve and abs(b) is less than a.
     cond2 =  b < 0 and a > 0 and abs(b) < a

     # if any of these conditions are met. negate the value of a and b 
     # and negate the value of answer as well.
     if cond1 or cond2:
         return negate(_getSum(negate(a),negate(b)))

     # otherwise run normally.
     return _getSum(a,b)


def _getSum(a, b):
     while (a):
         x = a & b
         y = a ^ b
         a = x << 1
         b = y
     return b
Sign up to request clarification or add additional context in comments.

1 Comment

This code would fail if you run it over cases such as a = -1 and b = 1, and the reason is that the conditionals in the code are not robust enough to handle this edge case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.