版权声明:本文为博主原创文章,未经允许不得转载。 https://blog.csdn.net/wem603947175/article/details/82228764
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):
s = list(s.replace(' ', ''))
i = j = l = 0
n = len(s)
while (i < n):
if s[j].isdigit():
curnum = cum = 0
while (i < n and s[i].isdigit()):
curnum = curnum * 10 + int(s[i])
i += 1
cum += 1
s[j] = curnum
l += 1
for k in range(1, cum):
s.remove(s[2 * l - 1])
i -= 1
j += 2
n -= cum - 1
i += 1
i = 0
while i < len(s) - 1:
if s[i] == '*':
s[i] = int(s[i - 1]) * int(s[i + 1])
del s[i + 1]
del s[i - 1]
i = 0
elif s[i] == '/':
s[i] = int(s[i - 1]) // int(s[i + 1])
del s[i + 1]
del s[i - 1]
i = 0
i += 1
i = 0
while i < len(s) - 1:
if s[i] == '+':
s[i] = int(s[i - 1]) + int(s[i + 1])
del s[i + 1]
del s[i - 1]
i = 0
elif s[i] == '-':
s[i] = int(s[i - 1]) - int(s[i + 1])
del s[i + 1]
del s[i - 1]
i = 0
i += 1
return s[0]