# basic-calculator-ii Try it on leetcode ## Description

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

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

 

Example 1:

Input: s = "3+2*2"
Output: 7

Example 2:

Input: s = " 3/2 "
Output: 1

Example 3:

Input: s = " 3+5 / 2 "
Output: 5

 

Constraints:

## Solution(Python) ```Python class Solution: def calculate(self, s: str) -> int: inner, outer, result, opt = 0, 0, 0, "+" for c in s + "+": if c == " ": continue if c.isdigit(): inner = 10 * inner + int(c) continue if opt == "+": result += outer outer = inner elif opt == "-": result += outer outer = -inner elif opt == "*": outer = outer * inner elif opt == "/": outer = int(outer / inner) inner, opt = 0, c return result + outer ```