Skip to content

Python interview practice/Netflix

Sum of Two Integers

Easymath · bit-manipulation

The problem

Given two integers a and b, return the sum of the two integers without using the operators + and -.

Function: def getSum(a,b):

Example input (a JSON list of arguments): [1, 2]
Expected output: 3

Operands and their mathematical sum fit signed 32-bit integers.

Hints

  1. XOR adds bits without carries and AND followed by a shift computes carries.
  2. Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.

Worked answer

Try it yourself first. When you are ready, open the answer below.

Show the Python answer
def getSum(a,b):
    mask=0xffffffff
    while b:a,b=(a^b)&mask,((a&b)<<1)&mask
    return a if a<2**31 else ~(a^mask)

Why it works

XOR adds bits without carries and AND followed by a shift computes carries. Use a 32-bit mask because Python negative integers have unbounded sign extension; decode the final signed result.

Complexity: O(32) iterations / O(1) fixed-width state.

Time: O(32) iterations · Space: O(1) fixed-width state

Run your own solution

Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Netflix.

See access and price

More free Netflix questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.