donnemartin / interactive-coding-challenges

120+ interactive Python coding interview challenges (algorithms and data structures). Includes Anki flashcards.
Other
29.44k stars 4.45k forks source link

Add two numbers without the + or - sign [Bug] #205

Open pupipipu opened 7 years ago

pupipipu commented 7 years ago

The bitwise add 2 integers solution will hit infinite loop for negative integers. The carry will keep increasing if the bit length is not bounded. Proposed solution:

    def sum_two(self,a,b):
                #max bit length, change to 32 for 32bit
        max_positive = 2 ** 64
        min_negative = -2 ** 64

        while b != 0:
            if b == max_positive:
                return a ^ min_negative
            a,b = a ^ b,(a&b)<<1
        return a