Write and Reuse an Add Function
Solve this ProblemEasy5 min
Topics
BasicsFunctions
Companies
TCSInfosysWipro
Given three integers
a, b and c, return their sum — and practise doing it with a helper function you write yourself.
A functionFunctionA named, reusable block of code. It receives inputs through parameters and sends a result back with return. packages one job so it can be used again and again. Here the job is "add two numbers". The values passed in a call are its argumentsArgumentsThe actual values given to a function when it is called, e.g. the 4 and 7 in addTwo(4, 7).; inside the function they are received by its parametersParametersThe named inputs in a function definition, e.g. x and y in addTwo(int x, int y).. Calling the same helper twice, with different arguments, adds all three numbers.
Test Case 1:
Input:a = 4, b = 7, c = 10
Output:21
Explanation:Add the first two (11), then add the third (21).
Test Case 2:
Input:a = -5, b = 5, c = 3
Output:3
Explanation:The first two cancel out, leaving just c.
Constraints
- ◆
-100000000 ≤ a, b, c ≤ 100000000
Try the Dry Run
Approach & Solutions
Do the Additions InlineGood
Write both additions directly inside sumOfThree: first a + b, then add c to that partial result. This works, but the "add two numbers" idea is written out by hand each time it is needed.
Time
O(1)Space
O(1)Java
class Solution {
public int sumOfThree(int a, int b, int c) {
int firstTwo = a + b;
int total = firstTwo + c;
return total;
}
}Call an addTwo() Helper TwiceOptimal
Define a small function addTwo(x, y) that returns x + y, then call it twice: once for a and b, and once more for that result and c. The logic lives in one place and is reused; the parameters x and y receive different values on each call.
Time
O(1)Space
O(1)Java
class Solution {
int addTwo(int x, int y) {
return x + y;
}
public int sumOfThree(int a, int b, int c) {
int firstTwo = addTwo(a, b);
return addTwo(firstTwo, c);
}
}