Medium
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:
1 <= s.length <= 3 * 105
s
consists of integers and operators ('+', '-', '*', '/')
separated by some number of spaces.s
represents a valid expression.[0, 231 - 1]
.class Solution {
fun calculate(s: String): Int {
var sum = 0
var tempSum = 0
var num = 0
var lastSign = '+'
for (i in 0 until s.length) {
val c = s[i]
if (Character.isDigit(c)) {
num = num * 10 + c.code - '0'.code
}
if (i == s.length - 1 || !Character.isDigit(c) && c != ' ') {
when (lastSign) {
'+' -> {
sum += tempSum
tempSum = num
}
'-' -> {
sum += tempSum
tempSum = -num
}
'*' -> tempSum *= num
'/' -> if (num != 0) {
tempSum /= num
}
}
lastSign = c
num = 0
}
}
sum += tempSum
return sum
}
}