Leetcode 練習:2021-12-25

December 25, 2021

Basic Calculator II

題號:227

var calculate = function(s) {
  s += '+'
  let wait = []
  let num = 0 
  let sign = '+'
  for (var i = 0; i < s.length; i++) {
    if (s[i] === ' ') continue
    if (!isNaN(s[i])) num = 10 * num + Number(s[i])
    else {
      if (sign === "+") {
        wait.push(num)
      } else if (sign === "-") {
        wait.push(-num)
      } else if (sign === "*") {
        wait.push(wait.pop() * num)
      } else {
        wait.push(Math.trunc(wait.pop() / num))
      }
      sign = s[i]
      num = 0
    }
  }
  return wait.reduce((a,b)=>a+b) 
}

Profile picture

Written by Wei Hung who is thinking. You should follow them on Twitter