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
- XOR adds bits without carries and AND followed by a shift computes carries.
- 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