leetcode 227. basic calculator 計算字串表示式的值 python
阿新 • • 發佈:2018-11-10
227. Basic Calculator II
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.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5分析:
整體思路是處理 * 、/ 再處理 + 、- ,此外,注意在python中 -3 // 2 = -2 與實際的計算是有1的區別,這個題在搜狗面試中遇到
# coding=utf-8 class Solution(object): def calculate(self, string): if not string: return '0' stack, num, sign = [], 0, '+' for i in range(0, len(string)): if string[i].isdigit(): num = num * 10 + int(string[i]) # 如果是連續的數字,得每次乘10 # i == len(string) - 1也要考慮,因為字串末尾有許多空格情況也要考慮 if not string[i].isdigit() and not string[i].isspace() or i == len(string) - 1: if sign == '+': stack.append(num) elif sign == '-': stack.append(-num) elif sign == '*': stack.append(stack.pop() * num) else: temp = stack.pop() assert num != 0 if temp // num < 0 and temp % num != 0: stack.append(temp // num + 1) # 負數除的情況 else: stack.append(temp // num) sign = string[i] num = 0 return sum(stack)