Leetcode 227 Basic Calculator II
Problem description
Given a string s
which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1]
.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
Example 1:
- Input: s = “3+2*2”
- Output: 7
Example 2:
- Input: s = “ 3/2 “
- Output: 1
Example 3:
- Input: s = “ 3+5 / 2 “
- Output: 5
Problem Solving Process
Use a variable
num
to accumulate digitsUse a variable
sign
to remember the last operator
For each character:
If digit → build the number
If operator or end of string:
Based on
sign
, apply the operation to the current num and update the stackReset
num
to 0Update
sign
to the current operator
The sum of all values in the stack gives the final resultThe sum of all values in the stack gives the final result
Code accomplish
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
sign = "+"
num = 0
s = s.replace(" ","") + "+"
for c in s:
if c.isdigit():
num = num * 10 + int(c)
else:
if sign == "+":
stack.append(num)
elif sign == "-":
stack.append(-num)
elif sign == "*":
stack.append(stack.pop() * num)
elif sign == "/":
last = stack.pop()
stack.append(int(last / float(num)))
num = 0
sign = c
return sum(stack)