227. Basic Calculator II
发布时间:2020-12-14 21:51:42 所属栏目:大数据 来源:网络整理
导读: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"
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" Example 2: Input: " 3/2 " Example 3: Input: " 3+5 / 2 " Note: You may assume that the given expression is always valid. Do not use the eval built-in library function. class Solution: def calculate(self,s): """ :type s: str :rtype: int """ op = ‘+‘ n = 0 l = [] for i in range(len(s)): if s[i].isdigit(): n = n *10 +int(s[i]) if not s[i].isdigit() and not s[i].isspace() or i == len(s)-1: if op == ‘+‘: l.append(n) if op == ‘-‘: l.append(-n) if op == ‘*‘: a = l.pop()*n l.append(a) if op == ‘/‘: a = int(l.pop()/n) l.append(a) op = s[i] n = 0 num = 0 while len(l): num += l.pop() return num (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |