Basic Calculator II
Evaluate a string with +, -, * and / in one pass, doing multiplication and division before addition and subtraction.
Given a string sint+-*/eval()
Example 1
Output: 7
Example 2
Output: 1
Example 3
Output: 5
The Idea
Some simple pocket calculators work out each step as soon as you press the next key. Type 3 + 2 × 2 into one of them and it adds 3 and 2 when you press ×, then doubles the 5, and shows 10. Ask a maths teacher and the answer is 7, because multiplication comes before addition. This problem wants the teacher's answer: Example 1, "3+2*2"
So reading the string from left to right raises a question. After reading 3 and +
Look at a longer expression, 14-3/2+2*3
The boxes in the row labelled "the string s" are its numbers and operators. The brackets under them group the boxes into pieces called terms: a number, the multiplications and divisions that follow it, and the sign in front. Term 1 is 14. Term 2 is -3/2, which is -1. Term 3 is +2*3, which is 6. Added up, 14 + (-1) + 6 gives 19.
Now look at where the colour changes: always at a +-*/+-
Solution Approach
Turning that idea into code means settling five things: reading a whole number, applying each operator, keeping the terms in a stack or in one variable, handling the last number, and dividing a negative term.
Reading a number
How does the code get 14 out of the characters 1 and 4? Each new digit cnumnum = num * 10 + (c - '0')c - '0''4'num
Applying the operator before each number
When is a number complete? Only when the next operator arrives, or the string ends. So the code remembers the operator that came before the number in opop+0+
If op+--op*/
Keeping the terms
Where do the terms go while the string is read? The familiar way is a stack, a list where items are added and removed only at the top. Each new term is pushed, a */
Look at the picture again, though: only the newest term ever changes. So one variable, termresult
The last number
What about the final 3 in 14-3/2+2*3*+
Dividing a negative term
The sign of a term is kept inside term14-3/2term/2/int
Java Solution
The method calculate
- First, set up four variables:
for the sum of the finished terms,result for the term still being built,term for the number being read, andnum for the operator before it, starting atop .'+' - Walk through the string with a
loop, from position 0 up to and includingfor . Inside the string, the characters.length() isc ; at the one extra position,s.charAt(i) is the imaginaryc .'+' - If
is a digit, add it toc withnum .num * 10 + (c - '0') - If
is an operator, applyc . Forop or+ , add- toterm and startresult asterm ornum . For-num or* , multiply or divide/ byterm . Then storenum inc and resetop to 0.num - After the loop, the last term is still in
, so returnterm .result + term
The main14-3/2
public class BasicCalculatorII {
public static int calculate(String s) {
int result = 0; // sum of the terms already finished
int term = 0; // the term still being multiplied or divided
int num = 0; // the number being read
char op = '+'; // the operator before num
for (int i = 0; i <= s.length(); i++) {
char c = i < s.length() ? s.charAt(i) : '+'; // a final '+' flushes the last number
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c != ' ') {
if (op == '+' || op == '-') {
result += term; // the previous term is finished
term = op == '+' ? num : -num;
} else if (op == '*') {
term = term * num;
} else {
term = term / num; // Java's '/' truncates toward zero
}
op = c;
num = 0;
}
}
return result + term;
}
public static void main(String[] args) {
System.out.println(calculate("3+2*2"));
System.out.println(calculate(" 3/2 "));
System.out.println(calculate(" 3+5 / 2 "));
System.out.println(calculate("14-3/2+2*3"));
System.out.println(calculate("14-3/2"));
System.out.println(calculate("2-3*2"));
System.out.println(calculate("100*2"));
System.out.println(calculate("42"));
}
}
Running it prints:
7
1
5
19
13
-4
200
42
The 7 at the top depends on the imaginary +*2"3+2*2"
The 13 below it comes from 14-3/2Math.floorDiv
The -4 comes from 2-3*2term*+term
The original implementation,
Complexity
The method reads the string once and keeps only four variables.
- Time: O(n), because the
loop looks at each of the n characters offor once, plus the imaginarys , and each step is a few arithmetic operations.+ - Space: O(1), because
,result ,term andnum are all the method keeps, however long the expression is. The stack version would hold one entry per term.op
With brackets in the expression, a stack is needed after all, to save result()