#371

Sum of Two Integers

Medium XOR + carry

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Add two integers without using + or -.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: add without using + or -.

Why this works: XOR adds bits but forgets carries; AND finds where carries happen, and shifting left moves them into place. Repeat until there's no carry.

Example: a = 5 (101), b = 3 (011)

sum 110, carry 010sum 100, carry 100sum 000, carry 1000sum 1000, carry 0 → 8

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Writing a while loop on b > 0 — the carry can be negative, so loop while b != 0.