Basic Calculator II
Description
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.
Solution(javascript)
/**
* @param {string} s
* @return {number}
*/
const calculate = function (s) {
const stack = []
let current = ''
const newS = `${s} `
for (const c of newS) {
if (c === '*' || c === '/' || c === '+' || c === '-' || c === ' ') {
if (current !== '') {
stack.push(parseInt(current, 10))
current = ''
}
while (Number.isInteger(stack[stack.length - 1]) && (
stack[stack.length - 2] === '/'
|| stack[stack.length - 2] === '*'
)) {
const b = stack.pop()
const operator = stack.pop()
const a = stack.pop()
stack.push(
operator === '*' ? a * b : Math.floor(a / b),
)
}
if (c !== ' ') {
stack.push(c)
}
} else {
current += c
}
// console.log(stack)
}
if (current !== '') {
stack.push(parseInt(current, 10))
current = ''
}
return stack.reduce((acc, item, index) => {
if (item === '-') {
stack[index + 1] = -stack[index + 1]
return acc
} if (item === '+') {
return acc
}
return acc + item
}, 0)
}