Adding Integers without Plus Operator in Python

🚀 Day 12 of #30DaysOfCode Back to Learning ! Today I explored a cool concept: 👉 Adding two integers without using the + operator in Python! Instead of +, I used bitwise operations: 🔹 XOR (^) → gives the sum without carry 🔹 AND (&) + LEFT SHIFT (<<) → handles the carry 💻 Code: def add_without_plus(a, b): while b != 0: carry = a & b # common bits (carry) a = a ^ b # sum without carry b = carry << 1 # shift carry to the left return a🧠 How it works: ✔️ XOR adds bits where only one is 1 ✔️ AND finds carry bits ✔️ Shift carry left and repeat until no carry remains 📌 Example: For 5 + 3: 5 = 101 3 = 011 ---------- XOR = 110 (6) AND = 001 → carry = 010 (after shift) Repeat until carry = 0 → result = 8 → Final Result = 8 ✅ ✨ This helped me understand how addition actually works at the binary level! #Python #Coding #30DaysOfCode #Programming #Bitwise #Learning #TechJourney

To view or add a comment, sign in

Explore content categories