leetcode227 Basic Calculator II

 1 """
 2 Implement a basic calculator to evaluate a simple expression string.
 3 The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
 4 Example 1:
 5 Input: "3+2*2"
 6 Output: 7
 7 Example 2:
 8 Input: " 3/2 "
 9 Output: 1
10 Example 3:
11 Input: " 3+5 / 2 "
12 Output: 5
13 """
14 """
15 这道题因为有空格字符,连续数字字符使得考虑情况有些复杂
16 为了保存好符号,用了一个sign变量,初始化为'+',保证其正常入栈
17 """
18 class Solution:
19     def calculate(self, s: str) -> int:
20         if not s:
21             return '0'
22         stack = []
23         sign = '+'  # !!!用一个sign实现将符号后置使用
24         num = 0
25         for i in range(len(s)):
26             if s[i].isdigit():
27                 num = num * 10 + int(s[i])  # ord(s[i]) - ord('0')
28             if not s[i].isdigit() and s[i] != ' ' or i == len(s) - 1:
29                 if sign == '-':  # 注意这里是sign
30                     stack.append(-num)
31                 elif sign == '+':
32                     stack.append(num)
33                 elif sign == '*':
34                     stack.append(stack.pop() * num)
35                 else:  # 因为python里向下取整,-1.5取整为-2
36                     temp = stack.pop()
37                     if temp // num < 0 and temp % num != 0:
38                         stack.append(temp // num + 1)
39                     else:
40                         stack.append(temp // num)
41                 sign = s[i]
42                 num = 0
43         res = 0
44         for j in range(len(stack)):
45             res += stack[j]
46         return res
47 if __name__ == '__main__':
48     ans = Solution()
49     s = "14-3/2"
50     ans.calculate(s)

 

posted @ 2020-03-06 17:09  yawenw  阅读(125)  评论(0编辑  收藏  举报