Data Structures & Algorithms Bit Manipulation
💡
Exercise 157

Sum of Two Integers 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Calculate the sum of two integers without using + or -. Use only bit manipulation.

# XOR gives sum without carry: 5^3 = 6 (110) # AND+shift gives carry: (5&3)<<1 = 2 (010) # Repeat until carry is 0 # 6 ^ 2 = 4, (6&2)<<1 = 4 # 4 ^ 4 = 0, (4&4)<<1 = 8 → result = 8

In Python, handle negative numbers with a 32-bit mask: 0xFFFFFFFF.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Add two integers without + or -. Print getSum(5, 3).
While b != 0: a, b = a^b, (a_old & b)<<1. Use 32-bit mask for Python negatives. You've got this — take it step by step!
🧪 Test Cases
Input
getSum(5, 3)
Expected
8
Test case 1
Input
getSum(-2, 3)
Expected
1
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.