Add Two Integers
EasyPrompt
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
Approaches
3 approaches with complexity analysis and trade-offs.
The most efficient, simple, and idiomatic approach is to use the language's built-in addition operator (+). This is the intended solution for a real-world scenario.
Algorithm
- Add
num1andnum2using the+operator. - Return the result.
Walkthrough
This solution leverages the computer's hardware for maximum performance. Processors have a specialized component, the Arithmetic Logic Unit (ALU), which is designed to perform arithmetic operations like addition extremely quickly, often in a single clock cycle. The + operator in Java (and most other languages) compiles down to a single machine instruction that utilizes the ALU. Therefore, return num1 + num2; is the most optimal way to compute the sum.
class Solution { public int sum(int num1, int num2) { return num1 + num2; }}Complexity
Time
O(1). The addition is a single, highly optimized hardware instruction.
Space
O(1). No additional space is used beyond what's needed to store the inputs and the return value.
Trade-offs
Pros
Maximum efficiency and performance.
Extremely simple, readable, and maintainable code.
This is the standard, idiomatic way to perform addition.
Cons
If the problem is posed in an interview to test knowledge of bit manipulation, this solution would miss the point.
Solutions
Solution
class Solution {public int sum(int num1, int num2) { return num1 + num2; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.