Sum of Two Integers
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Add two integers without using + or -.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What does a XOR b give for one column? What produces the carry?
- Hint 2Repeat until the carry is zero.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Adding on paper. First write the sum of each column ignoring carries (that is XOR). Then work out all the carries that should move to the next column (AND, shifted left). Now you have a new addition problem: partial sum plus carries. Repeat until there are no carries left. The partial sum is the answer.
- The obvious way
Increment one number b times with ++: far too slow.
- The key insight
While the carry (b) is not 0: new_sum = a XOR b; carry = (a AND b) shifted left by one; a = new_sum; b = carry. Return a. In Python integers are unbounded, so mask to 32 bits and convert a negative result back.
- The algorithm
- partial = a XOR b.
- carry = (a AND b) shifted left one.
- Set a = partial, b = carry.
- Stop when carry is 0; return a.
Watch it run
Examplea = 5 (101), b = 3 (011)
Partial sum without carry: 101 XOR 011 = 110 (6). Carries: 001 shifted left = 010 (2).
6 and 2
Where people slip
- In Python mask to 32 bits, otherwise a negative number makes the loop run forever.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def get_sum(a, b):
mask = 0xFFFFFFFF # keep 32 bits, like a real int
while b != 0:
partial = (a ^ b) & mask # sum of each column, ignoring carries
carry = ((a & b) << 1) & mask # carries move one column left
a, b = partial, carry
return a if a <= 0x7FFFFFFF else ~(a ^ mask) # turn a 32-bit negative back into a Python negativeNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.