227. Basic Calculator II - python3

227. Basic Calculator II

Given a string s which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

My Answer 1: Wrong Answer

class Solution:
    def calculate(self, s: str) -> int:
        s = s.strip()
        operator = ['+', '-', '*', '/']
        stack = []
        
        number = ''
        i = 0
        a = 0
        b = 0
        while i < len(s):
            if s[i] == '*':
                a = int(stack.pop())
                b = int(s[i+1])
                stack.append(str(a*b))
                i += 1
            elif s[i] == '/':
                a = int(stack.pop())
                b = int(s[i+1])
                stack.append(str(int(a/b)))
                i += 1
            else:
                stack.append(s[i])
            i += 1
        print(stack[0])
        
        result = 0
        a = stack.pop()
        while stack:
            op = stack.pop()
            b = stack.pop()
            print(a, op, b)
            if op == '+':
                result = int(a) + int(b)
                a = str(result)
            elif op == '-':
                result = int(a) - int(b)
                a = str(result)
        
        return result

이것도 150 번처럼 stack 을 이용해서 해보려했다..

근데 오늘 집중이 넘 안돼서 실패..

Solution 1: Runtime: 68 ms - 92.76% / Memory Usage: 16 MB - 33.40%

class Solution:
    def calculate(self, s: str) -> int:
        num, presign, stack=0, "+", []
        for i in s+'+':
            if i.isdigit():
                num = num*10 +int(i)
            elif i in '+-*/':
                if presign =='+':
                    stack.append(num)
                if presign =='-':
                    stack.append(-num)
                if presign =='*':
                    stack.append(stack.pop()*num)
                if presign == '/':
                    stack.append(math.trunc(stack.pop()/num))
                presign = i
                num = 0
        return sum(stack)

스택을 좀 더 간단하게 사용한 거..

이거 생각보다 쉬운거 같은데 왜그랬는지,,

좋은 웹페이지 즐겨찾기