Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
My code:
class Solution:
def calculate(self, s: str) -> int:
s=s.replace(" ","")
if s.isdigit():
return int(s)
i=0
result=0
tmp_record=[]
tmp_ops=[]
tmp_str=""
while i<len(s):
if s[i].isdigit():
tmp_str+=s[i]
i+=1
continue
else:
if len(tmp_ops)>0 and tmp_ops[-1]=='*':
tmp_interger2=int(tmp_str)
tmp_interger1=int(tmp_record[-1])
tmp_record[-1]=tmp_interger1*tmp_interger2
tmp_ops=tmp_ops[:-1]
elif len(tmp_ops)>0 and tmp_ops[-1]=='/':
tmp_interger2=int(tmp_str)
tmp_interger1=int(tmp_record[-1])
tmp_record[-1]=tmp_interger1/tmp_interger2
tmp_ops=tmp_ops[:-1]
else:
tmp_record.append(tmp_str)
tmp_ops.append(s[i])
tmp_str=""
i+=1
continue
if len(tmp_ops)>0 and tmp_ops[-1]=='*':
tmp_interger2=int(tmp_str)
tmp_interger1=int(tmp_record[-1])
tmp_record[-1]=tmp_interger1*tmp_interger2
tmp_ops=tmp_ops[:-1]
elif len(tmp_ops)>0 and tmp_ops[-1]=='/':
tmp_interger2=int(tmp_str)
tmp_interger1=int(tmp_record[-1])
tmp_record[-1]=tmp_interger1/tmp_interger2
tmp_ops=tmp_ops[:-1]
else:
tmp_record.append(tmp_str)
print(tmp_record)
print(tmp_ops)
result=int(tmp_record[0])
for i in range(len(tmp_ops)):
if tmp_ops[i]=="+":
result+=int(tmp_record[i+1])
else:
result-=int(tmp_record[i+1])
return result
Solution: https://leetcode.com/problems/basic-calculator-ii/