Basic Calculator II
Medium
Topics
You are given a line s holding an arithmetic expression built from non-negative whole numbers, the operators +, -, * and /, and any number of spaces. There are no parentheses and no unary minus. Evaluate it and return the result.
Use the usual precedence: * and / bind tighter than + and -, and operators of equal precedence apply left to right. Division is integer division that discards the fractional part (it rounds toward zero). Do not call any built-in expression evaluator.
Example 1
+ and -, so they take effect first even though the expression is read left to right. There are no brackets to worry about here, and division truncates toward zero rather than rounding. The expression evaluates to 10.Input: s = "4+3*2" Output: 10
Example 2
Input: s = " 9 / 4 " Output: 2
Example 3
Input: s = "20 - 6/4*3" Output: 17 Explanation: 6/4 is 1, times 3 is 3, and 20 - 3 = 17.
Constraints
- 1 <= s.length <= 3*10^5
- s is a valid expression; every number fits in a 32-bit signed integer.
- No division by zero occurs, and every intermediate and final value fits in a 32-bit signed integer.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Without parentheses, the expression is a sum of terms, where each term is a run of numbers joined by * and /. So you only need to finish each term as you read it and add it (with its sign) to a running total.
Approach
- Scan left to right, building the current number digit by digit and skipping spaces.
- Remember the operator that came before the current number (start with
+). - When you reach the next operator or the end: for
+or-, close the previous term into the total and start a new term of±number; for*or/, fold the number into the current term. - At the end, add the last term to the total. A stack of signed terms is the textbook version of the same idea; keeping just the total and the open term needs no stack.
Dry Run
s = "4+3*2". The trick is `last`: the pending term that a later * or / may still
modify, kept out of `total` until the next + or - commits it.
'4' digit, cur = 4
'+' op was '+', so commit last (0) to total and set last = 4
total 0, last 4, op '+'
'3' digit, cur = 3
'*' op was '+', so commit last (4) to total and set last = 3
total 4, last 3, op '*'
'2' digit, cur = 2
'#' sentinel. op was '*', so last = 3 * 2 = 6; nothing is committed
total 4, last 6
return total + last = 4 + 6 = 10
answer 10
Operators are applied one step LATE -- when the following number is complete, not
when the operator is seen. That is what makes multi-digit numbers work, since `cur`
is still being built with cur * 10 + digit when the operator arrives.
The loop runs to `len(s)` inclusive and reads a '#' sentinel past the end, which
is how the final term gets flushed. Loop only to len(s) - 1 and "4+3*2" returns 7,
dropping the last multiplication entirely; " 9 / 4 " returns 9.
Division truncates toward zero. With Python's `//`, "14-3/2" returns 12 instead of
13, because the pending term is -3 and -3 // 2 is -2 rather than -1.Complexity
- Time — O(n): one pass over the characters.
- Space — O(1): two running values instead of a stack.
Common Pitfalls
- Python's
//rounds toward negative infinity, so-7 // 2is -4. When the open term is negative, useint(a / b)to round toward zero. - Applying an operator when you see it, instead of when the number after it is complete, gets multi-digit numbers wrong.
- Do not forget to flush the last number when the string ends, including when it ends in spaces.
Full Solution — all languages
class Solution:
def calculate(self, s):
total = 0
last = 0
cur = 0
op = '+'
i = 0
while i <= len(s):
c = s[i] if i < len(s) else '#'
if c == ' ':
i += 1
continue
if c.isdigit():
cur = cur * 10 + int(c)
i += 1
continue
if op == '+':
total += last
last = cur
elif op == '-':
total += last
last = -cur
elif op == '*':
last = last * cur
else:
# truncate towards zero, which is not Python's // on negatives
last = int(last / cur)
op = c
cur = 0
i += 1
return total + lastimport java.util.*;
class Solution {
public int calculate(String s) {
long total = 0, last = 0, cur = 0;
char op = '+';
for (int i = 0; i <= s.length(); i++) {
char c = i < s.length() ? s.charAt(i) : '#';
if (c == ' ') continue;
if (c >= '0' && c <= '9') {
cur = cur * 10 + (c - '0');
continue;
}
if (op == '+') {
total += last;
last = cur;
} else if (op == '-') {
total += last;
last = -cur;
} else if (op == '*') last = last * cur;
else last = last / cur;
op = c;
cur = 0;
}
return (int) (total + last);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int calculate(string s) {
long long total = 0, last = 0, cur = 0;
char op = '+';
for (size_t i = 0; i <= s.size(); i++) {
char c = i < s.size() ? s[i] : '#';
if (c == ' ') continue;
if (isdigit((unsigned char)c)) {
cur = cur * 10 + (c - '0');
continue;
}
if (op == '+') {
total += last;
last = cur;
} else if (op == '-') {
total += last;
last = -cur;
} else if (op == '*') last = last * cur;
else last = last / cur;
op = c;
cur = 0;
}
return (int)(total + last);
}
};/**
* @param {string} s
* @return {number}
*/ var calculate = function(s) {
let total = 0, last = 0, cur = 0, op = '+';
for (let i = 0; i <= s.length; i++) {
const c = i < s.length ? s[i] : '#';
if (c === ' ') continue;
if (c >= '0' && c <= '9') {
cur = cur * 10 + (c.charCodeAt(0) - 48);
continue;
}
if (op === '+') {
total += last;
last = cur;
} else if (op === '-') {
total += last;
last = -cur;
} else if (op === '*') last = last * cur;
else last = Math.trunc(last / cur);
op = c;
cur = 0;
}
return total + last;
};