MEDIUM NC#149 Blind #11 Bit Manipulation
371. Sum of Two Integers
๐ Problem
Given two integers a and b, return the sum of the two integers without using the operators + and -.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Recursion reasoning pattern
๐ก Approach
- โ Use XOR for addition without carry: a ^ b
- โ Use AND and left shift for carry: (a & b) << 1
- โ Repeat until there's no carry
- โ Time: O(1) - max 32 iterations for 32-bit integers, Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse XOR for addition without carry: a ^ b
- โขUse AND and left shift for carry: (a & b) << 1
- โขRepeat until there's no carry
Common Pitfalls
- โขTime: O(1) - max 32 iterations for 32-bit integers, Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
getSum(1, 2); Expected:
3 Test Case 2
Not run Input:
getSum(2, 3); Expected:
5 Test Case 3
Not run Input:
getSum(-1, 1); Expected:
0 ๐ Code Editor
๐ค Output