website/content.en/ChapterFour/0200~0299/0227.Basic-Calculator-II.md
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
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:
1 <= s.length <= 3 * 10^5s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.s represents a valid expression.[0, 2^31 - 1].Given a string expression s, implement a basic calculator to evaluate it and return its value. Integer division should keep only the integer part.
preSign to the current traversed character. After traversing string s, sum the elements in the stack, which is the value of this string expression. Time complexity is O(n), and space complexity is O(n).package leetcode
func calculate(s string) int {
stack, preSign, num, res := []int{}, '+', 0, 0
for i, ch := range s {
isDigit := '0' <= ch && ch <= '9'
if isDigit {
num = num*10 + int(ch-'0')
}
if !isDigit && ch != ' ' || i == len(s)-1 {
switch preSign {
case '+':
stack = append(stack, num)
case '-':
stack = append(stack, -num)
case '*':
stack[len(stack)-1] *= num
default:
stack[len(stack)-1] /= num
}
preSign = ch
num = 0
}
}
for _, v := range stack {
res += v
}
return res
}