topic
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.
Thinking
1, a computation is in the definition of the functions, string contains only * / calculation
2, according to the first string separated +
3, if there are fragments - according to - split. For each split segment, run multiplication and division calculations, and the resulting value together
answer
class Solution:
def calculate(self, s: str) -> int:
def multiply(string):
nums = string.split("*")
ans = 1
for n in nums:
if "/" in n:
divides = n.split("/")
ans *= int(divides[0])
for i in range(1,len(divides)):
ans = ans//int(divides[i])
else:
ans *= int(n)
return ans
s = s.replace(" ","")
s = s.split("+")
ans = 0
for num in s:
if "-" in num:
num_reduce = num.split("-")
temp_reduce = multiply(num_reduce[0])
for i_r in range(1,len(num_reduce)):
temp_reduce -= multiply(num_reduce[i_r])
ans += temp_reduce
else:
ans += multiply(num)
return ans
ps:
The answer is, there are a stack of ideas, not bad