计算器实现

class Solution:
    """
    @param s: the expression string
    @return: the answer
    """
    def calculate(self, s):
        # Write your code here
        order = {'+': 0, '-':0, '*': 1, '/':1}
        stack = []
        num = 0
        
        for c in s:
            if c.isdigit():
                num = num * 10 + int(c)
                
            if c in '+-*/':
                while stack and stack[-1] != '(' and order[stack[-1]] >= order[c]:
                    op = stack.pop()
                    pre = stack.pop()
                    num = self.calc(pre, num, op)
                stack.append(num)
                stack.append(c)
                num = 0
                
            if c is '(':
                stack.append(c)
                
            if c is ')':
                while stack[-1] != '(':
                    op = stack.pop()
                    pre = stack.pop()
                    num = self.calc(pre, num, op)
                stack.pop()
        
        while stack:
            op = stack.pop()
            pre = stack.pop()
            num = self.calc(pre, num, op)
            
        return num
        

    def calc(self, a, b, op):
        if op == '+':
            return a + b
        if op == '-':
            return a - b
        if op == '*':
            return a * b
        if op == '/':
            return a // b

class Solution:
    """
    @param s: the expression string
    @return: the answer
    """
    def __init__(self) :
        self.i = 0
    def parseExpr(self ,s) :
        nums = []
        op = '+'
        while self.i < len(s) and op != ')' :   #遇到右括号退出递归
            if s[self.i] == ' ' :
                self.i += 1
                continue
            if s[self.i] == '(' :    	#遇到左括号进入递归
                self.i += 1         
                n = self.parseExpr(s)
            else :							
                n = self.parseNum(s)	#字符串转化数字
            if  op == '+' :            #加法
                nums.append(n)		
            elif op == '-' :			#减法
                nums.append(-n)		
            elif op == '*' :			#乘法
                nums[-1] *= n			
            elif op == '/' :			#除法
                nums[-1] //= n	
            if self.i >= len(s) :
                break
            op = s[self.i]
            self.i += 1
        res = 0
        for n in nums :									
            res += n
        return res
    def parseNum(self, s) :
        n = 0
        while self.i < len(s) and s[self.i] >= '0' and s[self.i] <='9' :
            n = ord(s[self.i]) - ord('0') + 10 * n
            self.i += 1
        return n
    def calculate(self, s):
        # Write your code here
        return self.parseExpr(s)

全部评论

相关推荐

06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务