GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #224 - Basic Calculator - LeetCode JavaScript Solutions

Back to all solutions

#224 - Basic Calculator

Hard • View on LeetCode • View on GitHub
String Math Stack Recursion

Problem Description

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Solution

/**
 * @param {string} s
 * @return {number}
 */
var calculate = function(s) {
  const stack = [];
  let result = 0;

  for (let i = 0, sign = 1; i < s.length; i += 1) {
    if (s[i] >= '0' && s[i] <= '9') {
      let value = 0;
      while (s[i] >= '0' && s[i] <= '9') {
        value = (value * 10) + (s[i] - '0');
        i += 1;
      }
      result += value * sign;
      i -= 1;
    } else if (s[i] === '+') {
      sign = 1;
    } else if (s[i] === '-') {
      sign = -1;
    } else if (s[i] === '(') {
      stack.push(result, sign);
      result = 0;
      sign = 1;
    } else if (s[i] === ')') {
      result = stack.pop() * result;
      result += stack.pop();
    }
  }

  return result;
};
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.