# Basic Calculator II Problem

0 like 0 dislike
202 views

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.

Example 1:

```Input: "3+2*2"
Output: 7
```

Example 2:

```Input: " 3/2 "
Output: 1```

Example 3:

```Input: " 3+5 / 2 "
Output: 5
```

Note:

• You may assume that the given expression is always valid.
• Do not use the `eval` built-in library function.

### For Indian Students- INR 360/- || For International Students- \$9.99/-

S.No.

Course Name

Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence

Apply Coupon

2.

Natural Language Processing-NLP with Deep Learning in Python Apply Coupon

3.

Computer Vision OpenCV Python | YOLO| Deep Learning in Colab Apply Coupon

0 like 0 dislike
by Goeduhub's Expert (2.3k points)

Pretty easy with stack, we would add value into stack if we encounter +/ - and for mul / div we would modify the exsting value into the stack and it again into stack.

class Solution:

def calculate(self, s):

num, stack, sign = 0, [], "+"

for i in range(len(s)):

if s[i].isdigit():

num = num * 10 + int(s[i])

if s[i] in "+-*/" or i == len(s) - 1:

if sign == "+":

stack.append(num)

elif sign == "-":

stack.append(-num)

elif sign == "*":

stack.append(stack.pop()*num)

else:

stack.append(int(stack.pop()/num))

num = 0

sign = s[i]

return sum(stack)

eg : ans = Solution()

ans.calculate("3+2*2")

Output -

7