Add Numbers Without Plus in JavaScript Using Bitwise Operators

🚀 Add Two Numbers WITHOUT Using + in JavaScript 😳 Here’s a classic trick that interviewers LOVE 👇 Instead of using +, we use bitwise operators: 👉 XOR (^) → gives sum without carry 👉 AND (&) → gives carry 👉 << 1 → shifts carry to correct position 💡 Logic: Keep adding the partial sum and carry until carry becomes 0 Why this matters? Because this is exactly how computers perform addition internally at the binary level. 🧠 It’s not just a trick — it’s understanding how systems really work. 🔥 Example: 5 (0101) + 3 (0011) → Result = 8 (1000) 🎯 Where this helps: ✔️ Coding interviews ✔️ Bit manipulation problems ✔️ Deep understanding of low-level operations ✅ Using Bitwise Operators: function sum(a, b) {   while (b !== 0) {    let carry = a & b;  // common bits (carry)    a = a ^ b;      // sum without carry    b = carry << 1;   // shift carry   }   return a; } 🔢 Example: sum(5, 3) First convert numbers to binary: 5 = 0101 3 = 0011 🧠 Core Idea This function mimics how addition works at the bit level: XOR (^) → adds bits without carry AND (&) → finds the carry << 1 → moves carry to the next position 🔁 Step-by-Step Execution 👉 Iteration 1 a = 0101 (5) b = 0011 (3) Step 1: carry carry = a & b = 0101 & 0011 = 0001 Step 2: sum without carry a = a ^ b = 0101 ^ 0011 = 0110 (6) Step 3: shift carry b = carry << 1 = 0001 << 1 = 0010 (2) 👉 Iteration 2 a = 0110 (6) b = 0010 (2) Step 1: carry carry = 0110 & 0010 = 0010 Step 2: sum without carry a = 0110 ^ 0010 = 0100 (4) Step 3: shift carry b = 0010 << 1 = 0100 (4) 👉 Iteration 3 a = 0100 (4) b = 0100 (4) Step 1: carry carry = 0100 & 0100 = 0100 Step 2: sum without carry a = 0100 ^ 0100 = 0000 (0) Step 3: shift carry b = 0100 << 1 = 1000 (8) 👉 Iteration 4 a = 0000 (0) b = 1000 (8) Step 1: carry carry = 0000 & 1000 = 0000 Step 2: sum without carry a = 0000 ^ 1000 = 1000 (8) Step 3: shift carry b = 0000 << 1 = 0000 ✅ Loop Ends Now b = 0, so loop stops. 👉 Final Answer: a = 1000 (8) 🎯 Final Understanding (Important for Interviews) We keep adding partial sum (a ^ b) And carry separately ((a & b) << 1) Repeat until no carry left 🔥 One-Line Intuition 👉 “This is binary addition where we separate sum and carry, then combine them until carry becomes zero.” Follow for more real-world coding insights 🚀 #javascript #coding #webdevelopment #programming #100daysofcode #developer #tech #interviewprep #bitwise #learncoding #dsa #ai

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories