Sum of Two Integers
Sum of Two Integers
Section titled “Sum of Two Integers”
Medium
Day 3 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Given two integers a and b, return the sum of the two integers without using the operators + and -.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
a = 1, b = 2 - Output:
3
Example 2:
- Input:
a = 2, b = 3 - Output:
5
Constraints:
-1000 <= a, b <= 1000
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Bitwise XOR calculates addition without carry; bitwise AND shifted left calculates carry.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Bitwise Operations (XOR + AND)
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD A["Input Integer / Bits"] --> B["Apply Bitwise Operation (AND / XOR / Shift)"] B --> C{"Check Bit Condition"} C -- "Condition Met" --> D["Update Bit Count / Result"] C -- "Continue" --> E["Shift Bits (>>> 1 or & n-1)"] E --> B D --> F["Return Final Result"]🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function getSum(a, b) { while (b !== 0) { let carry = (a & b) << 1; a = a ^ b; b = carry; } return a;}- Time Complexity:
O(1) - Space Complexity:
O(1) - Explanation: Iterative bitwise carry.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function getSum(a, b) { while (b !== 0) { let carry = (a & b) << 1; a = a ^ b; b = carry; } return a;}- Time Complexity:
O(1) - Space Complexity:
O(1) - Explanation: Bitwise sum using XOR and shift.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”Use XOR for bitwise sum and AND shifted for carry until carry becomes zero.
💡 Progressive Hints
Section titled “💡 Progressive Hints”- XOR gives sum without carry.
- AND left shifted by 1 gives carry.