[Bit Operation-Simple] Interview Question 17.01. Addition without plus sign (review)

[Title]
Design a function to add two numbers. Do not use + or other arithmetic operators.
[Example]
Input: a = 1, b = 1
Output: 2
[Prompt]
Both a and b may be negative or 0. The
result will not overflow a 32-bit integer
[Code]
[Python]
Insert picture description here

class Solution:
    def add(self, a: int, b: int) -> int:
        a &= 0xFFFFFFFF
        b &= 0xFFFFFFFF
        print(a)
        print(b)
        while b != 0:
            carry = a & b
            a ^= b
            b = ((carry) << 1) & 0xFFFFFFFF        
        return a if a < 0x80000000 else ~(a^0xFFFFFFFF)

Guess you like

Origin blog.csdn.net/kz_java/article/details/115264651