# Basic Calculator II

## Problem

Given a string `s` which represents an expression, *evaluate this expression and return its value*.&#x20;

The integer division should truncate toward zero.

(The difference between this and Basic Calculator I is that in here we have all the operands and no paranthese, while in Basic Calculator I we only had '+' and '-' and parantheses.)

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MR1LnXSj19hU-3fO3Mb%2F-MR1MpE85vHHQMVVABZo%2FScreen%20Shot%202021-01-14%20at%2012.28.53%20PM.png?alt=media\&token=003a1437-2b82-4939-8edb-f2e6eb071b61)

### Thought Process

* Multiplication and division need to be handled before addition and subtraction
* Once again here we are saving the previous sign like in Basic Calculator I

![](https://1063826111-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGdx41c9p2PMgIHbUTK%2F-MR1LnXSj19hU-3fO3Mb%2F-MR1O1c2La3_KHXvv5J9%2FIMG_FB76F7A3E735-1.jpeg?alt=media\&token=db7e5f65-96a0-4bc0-a1c4-b6c5e085a049)

## Solution&#x20;

```
class Solution:
    def calculate(self, s: str) -> int:
        stack = []
        numbers = set("0123456789")
        num = 0
        operands = "*+-/"
        sign = '+'
        
        for i in range(len(s)):
            if s[i] in numbers:
                num = 10*num + int(s[i])
            
            if s[i] in operands or i == len(s)-1:
                if sign == '+':
                    stack.append(num)
                elif sign == '-':
                    num*=-1
                    stack.append(num)
                elif sign == '*':
                    prev = stack.pop()
                    stack.append(prev*num)
                elif sign == '/':
                    prev = stack.pop()
                    stack.append(int(prev/num))
                num = 0
                sign = s[i]
        
        return sum(stack)
                    
```

## Time Complexity

* **Time:** O(n)
* **Space:** O(n)
