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.
Example 1:
Input: s = "3+2*2"
Output: 7Example 2:
Input: s = " 3/2 "
Output: 1Example 3:
Input: s = " 3+5 / 2 "
Output: 5Constraints:
1 <= s.length <= 3 * 105sconsists of integers and operators('+', '-', '*', '/')separated by some number of spaces.srepresents a valid expression.- All the integers in the expression are non-negative integers in the range
[0, 231 - 1]. - The answer is guaranteed to fit in a 32-bit integer.
# @lc code=start
using LeetCode
function calculate_ii(s::String)::Int
num, stk, sign = 0, Int64[], '+'
for (i, c) in enumerate(s)
isdigit(c) && (num = 10 * num + parse(Int, c))
if c in ['-', '+', '/', '*'] || i == length(s)
if sign == '+'
push!(stk, num)
elseif sign == '-'
push!(stk, -num)
elseif sign == '*'
push!(stk, pop!(stk) * num)
elseif sign == '/'
push!(stk, pop!(stk) ÷ num)
end
num = 0
sign = c
end
end
return sum(stk)
end
# @lc code=endcalculate_ii (generic function with 1 method)
This page was generated using DemoCards.jl and Literate.jl.