题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 返回表达式的值 # @param s string字符串 待计算的表达式 # @return int整型 # class Solution: def solve(self , s: str) -> int: # write code here num = 0 i = 0 n = len(s) stack = [] res = 0 op = '+' while i < n: if s[i] >= '0' and s[i] <= '9': num = num * 10 + int(s[i]) if s[i] == '(': cnt = 0 j = i while i < n: if s[i] == '(': cnt += 1 elif s[i] == ')': cnt -= 1 if cnt == 0: break i += 1 num = self.solve(s[j + 1 : i]) if s[i] == '+' or s[i] == '-' or s[i] == '*' or s[i] == '/' or i == n - 1: if op == '+': stack.append(num) elif op == '-': stack.append(-num) elif op == '*': stack[-1] *= num; else: if stack[-1] > 0: stack[-1] /= num else: t = -stack[-1] / num stack[-1] = -t num = 0 op = s[i] i += 1 while stack: res += stack.pop() return res