LeetCode 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
Note: Do not use the eval built-in library function.
思路:
这道题刚开始分+ - * /四种情况处理,最后发现情况太多,处理不了。
后来想下, 把乘除的当成一块。 那么问题会分成两个问题, 一个是处理加减,一个是处理乘除。
AC代码:
1 class Solution(object): 2 def mul_div(self, s): 3 n = len(s) 4 for i in xrange(1, n): 5 if s[i] == "*": 6 for j in xrange(i+1, n+1): 7 if j==n: 8 return int(s[:i]) * int(s[i+1:j]) 9 if s[j] == "+" or s[j] == "-" or s[j] == "*" or s[j] == "/": 10 ss = str( int(s[:i]) * int(s[i+1:j]) ) 11 return self.mul_div( ss + s[j:]) 12 13 if s[i] == "/": 14 for j in xrange(i+1, n+1): 15 if j==n: 16 return int(s[:i]) / int(s[i+1:j]) 17 if s[j] == "+" or s[j] == "-" or s[j] == "*" or s[j] == "/": 18 ss = str( int(s[:i]) / int(s[i+1:j]) ) 19 return self.mul_div( ss + s[j:]) 20 21 return int(s) 22 23 def calculate(self, s): 24 """ 25 :type s: str 26 :rtype: int 27 """ 28 s = s.replace(" ", "") 29 n = len(s) 30 ans = 0 31 flag = 1 32 ss = "" 33 for i in range(n): 34 if s[i] == "+": 35 ans += flag * self.mul_div(ss) 36 ss = "" 37 flag = 1 38 elif s[i] == "-": 39 ans += flag * self.mul_div(ss) 40 ss = "" 41 flag = -1 42 else : 43 ss += s[i] 44 ans += flag * self.mul_div(ss) 45 46 return ans

浙公网安备 33010602011771号