Difficulty: Easy | Acceptance: 88.00% | Paid: No Topics: Math
Given two integers num1 and num2, return the sum of the two integers.
- Examples
- Constraints
- Direct Addition
- Bitwise Manipulation
Examples
Input: num1 = 12, num2 = 5
Output: 17
Explanation: num1 + num2 = 12 + 5 = 17
Input: num1 = -10, num2 = 4
Output: -6
Explanation: num1 + num2 = -10 + 4 = -6
Constraints
-100 <= num1, num2 <= 100
Direct Addition
Intuition The most straightforward way to add two integers is to use the built-in addition operator provided by the programming language.
Steps
- Return the result of
num1 + num2.
python
class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2Complexity
- Time: O(1)
- Space: O(1)
- Notes: This is the optimal solution for readability and performance.
Bitwise Manipulation
Intuition
We can simulate addition using bitwise operators. The XOR (^) operation handles the sum without carry, while the AND (&) operation followed by a left shift (<<) calculates the carry. We repeat this until there is no carry left.
Steps
- While
num2is not 0:- Calculate the carry where both bits are 1:
carry = num1 & num2. - Calculate the sum without carry:
num1 = num1 ^ num2. - Shift the carry to the left by 1 bit:
num2 = carry << 1.
- Calculate the carry where both bits are 1:
- Return
num1.
python
class Solution:
def sum(self, num1: int, num2: int) -> int:
while num2 != 0:
carry = num1 & num2
num1 = num1 ^ num2
num2 = carry << 1
return num1Complexity
- Time: O(1) - The loop runs at most 32 times (for 32-bit integers).
- Space: O(1)
- Notes: This approach is useful for understanding low-level arithmetic but is generally slower than direct addition.