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