Sum of Two Numbers
Solve this ProblemEasy5 min
Topics
BasicsVariablesMath
Companies
TCSInfosysWipro
Given two integers
a and b, return their sum.
The point here is the variableVariableA named storage slot that holds a value of a fixed type (such as int) so it can be used later.: a named box that holds a value. The first solution stores the answer in a variable before returning it; the second returns the expression directly. Both are correct — storing first is handy when you want to print or reuse the value, returning directly is shorter. The constraints keep the sum safely inside the range an int can hold, so there is no overflowInteger OverflowWhen a result is too large for its type, so it wraps around to a wrong (often negative) value..
Test Case 1:
Input:a = 12, b = 30
Output:42
Explanation:Plain addition of two positive values.
Test Case 2:
Input:a = -8, b = 3
Output:-5
Explanation:Adding a smaller positive to a negative still leaves a negative total.
Constraints
- ◆
-100000000 ≤ a, b ≤ 100000000
Try the Dry Run
Approach & Solutions
Store the Sum in a VariableGood
Create a variable called total, store a + b in it, then return total. Giving the result a name is a habit worth building: it makes the value easy to print, inspect or reuse before it leaves the function.
Time
O(1)Space
O(1)Java
class Solution {
public int addTwoNumbers(int a, int b) {
int total = a + b;
return total;
}
}Return the Expression DirectlyOptimal
A return statement accepts any expression, so the addition can be written right there: return a + b. No extra variable is needed when the value is used only once.
Time
O(1)Space
O(1)Java
class Solution {
public int addTwoNumbers(int a, int b) {
return a + b;
}
}