num1
and num2
, return the sum of the two integers.
Example 1:
Input: num1 = 12, num2 = 5 Output: 17 Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.
Example 2:
Input: num1 = -10, num2 = 4 Output: -6 Explanation: num1 + num2 = -6, so -6 is returned.
Constraints:
-100 <= num1, num2 <= 100
The problem asks to add two integers. There are two main approaches:
Solution 1: Direct Addition
This is the most straightforward approach. We leverage the built-in addition operator of the programming language to directly add the two input integers.
Code: All the provided code snippets (Python, Java, C++, Go, TypeScript, Rust, C) simply return num1 + num2
.
Time Complexity: O(1) - Constant time. Addition is a basic operation performed in constant time.
Space Complexity: O(1) - Constant space. We use a fixed amount of memory regardless of the input size.
Solution 2: Bit Manipulation (Binary Addition)
This solution simulates binary addition using bitwise operators. It iteratively adds bits without using the '+' operator.
Algorithm:
while
loop that continues as long as num2
(the second number) is not zero.carry = (num1 & num2) << 1
: This line calculates the carry bits. The bitwise AND (&
) identifies bits where both num1
and num2
are 1 (resulting in a carry). The left shift (<< 1
) moves the carry bits one position to the left, simulating the carry in binary addition. Note that in some languages, like C++, explicit casting to unsigned int
might be needed to prevent undefined behavior with left bit shifts.num1 ^= num2
: This line performs bitwise XOR (^
), which adds the bits without considering the carry. If either bit is 1, the result is 1; if both are 1 or both are 0, the result is 0.num2 = carry
: The carry is assigned to num2
, preparing for the next iteration.num2
becomes 0).num1
holds the sum. In Python, additional handling is necessary to correctly manage negative numbers through bitwise operations and masking.Time Complexity: O(log n), where n is the magnitude of the larger number. The number of iterations is proportional to the number of bits in the larger number. In practice this is still considered O(1) because the maximum values of num1
and num2
are constrained.
Space Complexity: O(1) - Constant space.
Which Solution to Choose?
For this specific problem with the given constraints (-100 <= num1, num2 <= 100), Solution 1 (direct addition) is the preferred approach due to its simplicity and readability. Solution 2 is primarily for demonstrating bit manipulation techniques and might be relevant in situations where addition is not directly supported, or for educational purposes. The performance difference between the two will be negligible for numbers within the specified range.