题目
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.
思路
1、定义一个计算乘除的函数,字符串只包含 * / 运算
2、将字符串先按照 + 分开
3、如果片段中有 -,按照 - 拆分。对每个拆分的片段,先运行乘除计算,然后将得到的值加起来
答案
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:
答案里有个思路是用 栈,也不错