標籤(空格分隔): LeetCodepython
做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.me/c++
題目地址:https://leetcode.com/problems/basic-calculator-ii/description/git
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.express
Example 1:app
Input: "3+2*2" Output: 7
Example 2:ide
Input: " 3/2 " Output: 1
Example 3:ui
Input: " 3+5 / 2 " Output: 5
Note:lua
給算數表達式求值。spa
直接使用eval能夠過。。而後算法的話,使用下下面的方法:
用num保存上一個數字,用pre_op保存上一個操做符。當遇到新的操做符的時候,須要根據pre_op進行操做。乘除的優先級高於加減。因此有如下規則:
以前的運算符是+,那麼須要把以前的數字num進棧,而後等待下一個操做數的到來。
以前的運算符是-,那麼須要把以前的數字求反-num進棧,而後等待下一個操做數的到來。
以前的運算符是×,那麼須要馬上出棧和以前的數字相乘,從新進棧,而後等待下一個操做數的到來。
以前的運算符是/,那麼須要馬上出棧和以前的數字相除,從新進棧,而後等待下一個操做數的到來。
注意比較的都是以前的操做符和操做數,如今遇到的操做符是沒有什麼用的。
另外,坑爹的Python地板除。。好比-3//2=2的,和c++不同。所以真正操做的時候若是遇到負數,使用的用浮點除再取整的方式得到和c++同樣的結果。
class Solution: def calculate(self, s): """ :type s: str :rtype: int """ stack = [] pre_op = '+' num = 0 for i, each in enumerate(s): if each.isdigit(): num = 10 * num + int(each) if i == len(s) - 1 or each in '+-*/': if pre_op == '+': stack.append(num) elif pre_op == '-': stack.append(-num) elif pre_op == '*': stack.append(stack.pop() * num) elif pre_op == '/': top = stack.pop() if top < 0: stack.append(int(top / num)) else: stack.append(top // num) pre_op = each num = 0 return sum(stack)
2018 年 6 月 27 日 ———— 陽光明媚,心情大好,抓緊科研啊