Build a Simple Four-Operation Calculator
Solve this ProblemEasy10 min
Topics
BasicsConditionals
Companies
TCSInfosysWipro
Given two integers
a and b and an operator op — one of "+", "-", "*", or "/" — perform that operation on a and b and return the result.
The if-else chainIf-Else ChainA sequence of if / else-if / else blocks, tried in order until one condition matches. version tests each operator string one at a time. The switch statementSwitch StatementA multi-way branch on a single value's exact matches — jumps directly to the matching case instead of testing conditions sequentially. version expresses the exact same four-way choice more directly, since every branch is an exact match against one fixed value rather than a general condition.
Test Case 1:
Input:a = 6, b = 3, op = "+"
Output:9
Explanation:6 + 3 = 9.
Test Case 2:
Input:a = 10, b = 4, op = "-"
Output:6
Explanation:10 - 4 = 6.
Test Case 3:
Input:a = 5, b = 6, op = "*"
Output:30
Explanation:5 * 6 = 30.
Constraints
- ◆
-1000 ≤ a ≤ 1000 - ◆
-1000 ≤ b ≤ 1000 - ◆
op is one of "+", "-", "*", "/" - ◆
b ≠ 0 whenever op is "/"
Try the Dry Run
Approach & Solutions
If-Else ChainGood
Compare op against each operator symbol in turn — "+", then "-", then "*" — performing the matching arithmetic as soon as one matches. Anything left over (not caught by the first three) is treated as division.
Time
O(1)Space
O(1)Java
1class Solution {
2 public int calculate(int a, int b, String op) {
3 if (op.equals("+")) {
4 return a + b;
5 } else if (op.equals("-")) {
6 return a - b;
7 } else if (op.equals("*")) {
8 return a * b;
9 } else {
10 return a / b;
11 }
12 }
13}Switch Statement on the OperatorOptimal
With a fixed, small set of exact-match choices like this, a switch says the same thing as the if-else chain more directly: it jumps straight to whichever case matches op, instead of testing one condition after another. The operator is a single character, so switching on that one character (rather than the whole string) keeps the comparison as simple as possible in every language.
Time
O(1)Space
O(1)Java
1class Solution {
2 public int calculate(int a, int b, String op) {
3 switch (op.charAt(0)) {
4 case '+': return a + b;
5 case '-': return a - b;
6 case '*': return a * b;
7 default: return a / b;
8 }
9 }
10}