227. Basic Calculator II

227. Basic Calculator II

class Solution:
    def calculate(self, s: str) -> int:
        it=iter(re.split(r'([\+\-\*\/])',s))
        last=ans=int(next(it))
        for op in it:
            n=int(next(it))
            if op in '+-':
                if op=='-':n=-n
                ans+=n
            else:
                if op=='*':
                    n=last*n
                else:
                    n=int(last/n)
                ans=ans-last+n
            last=n
        return ans

注意这个不用stack的写法

你可能感兴趣的:(leetcode)