Algorithm


Problem Name: 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.

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.
  • 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.

Code Examples

#1 Code Example with C Programming

Code - C Programming


typedef struct {
    int *p;
    int sz;
    int n;
} s_t;
int parse(char **sp, int *k) {
    char *s = *sp;
    
    while (*s == ' ') s ++;
​
    *k = 0;
    
    if (*s == 0) return 0;
    
    if (*s == '+' || *s == '-' || *s == '*' || *s == '/') {
        *k = *s == '+' ? 1 :
             *s == '-' ? 2 :
             *s == '*' ? 3 : 4;
        *sp = ++ s;
        return 1;
    }
    
    while (*s >= '0' && *s  < = '9') {
        *k = (*k) * 10 + *s - '0';
        s ++;
    }
    *sp = s;
    return 2;
}
void push(s_t *stack, int k) {
    if (stack->sz == stack->n) {
        stack->sz *= 2;
        stack->p = realloc(stack->p, stack->sz * sizeof(int));
        //assert(stack->p);
    }
    stack->p[stack->n ++] = k;
}
int low_op(s_t *ops, int k) {
    const int priority[] = { 0, 1, 1, 2, 2 }; // null, +, -, *, /
    return (priority[ops->p[ops->n - 1]] >= priority[k]) ? 1 : 0;
}
int calculate(char* s) {
    s_t data = { 0 }, ops = { 0 };
    int x, k, d1, d2, o;
​
    data.n = ops.n = 0;
    data.sz = ops.sz = 10;
    data.p = malloc(data.sz * sizeof(int));
    ops.p = malloc(ops.sz * sizeof(int));
    
    push(&data, 0); // put a zero in case of with a null input
    push(&ops, 0);  // put a null operator on top of operator stack
    
    do {
        x = parse(&s, &k);
        if (x == 2) {   // data, push to stack
            push(&data, k);
        } else {        // operator
            while (low_op(&ops, k)) {
                o = ops.p[-- ops.n];
                if (o == 0) break;      // the end
                d2 = data.p[-- data.n];
                d1 = data.p[-- data.n];
                switch (o) {
                    case 1: // '+'
                        d1 = d1 + d2;
                        break;
                    case 2: // '-'
                        d1 = d1 - d2;
                        break;
                    case 3: // '*'
                        d1 = d1 * d2;
                        break;
                    case 4: // '/'
                        d1 = d1 / d2;
                        break;
                    default:
                        break;
                }
                push(&data, d1);
            }
            if (k) push(&ops, k);
        }
    } while (x);
    
    //assert(ops.n == 0);
    k = data.p[data.n - 1];
    
    free(data.p);
    free(ops.p);
    
    return k;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "3+2*2"

Output

x
+
cmd
7

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
private:
    unordered_mapstk;
        int tmp = 0;
        char op = '+';
        for(int i = 0; i  <  s.size(); i++){
            char c = s[i];
            if(c == ' ') continue;
            if(isdigit(c)) tmp = tmp*10 + c - '0';
            if(!isdigit(c)){
                if(op == '+')
                    stk.push(tmp);
                else if(op == '-')
                    stk.push(-tmp);
                else if(op == '*'){
                    int n = stk.top();
                    stk.pop();
                    stk.push(n*tmp);
                }
                else if(op == '/'){
                    int n = stk.top();
                    stk.pop();
                    stk.push(n/tmp);
                }
                op = c;
                tmp = 0;
            }
        }
        int res = 0;
        while(!stk.empty()) res += stk.top(), stk.pop();
        return res;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "3+2*2"

Output

x
+
cmd
7

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int calculate(String s) {
    int currNum = 0;
    int prevNum = 0;
    int result = 0;
    char operation = '+';
    for (int i = 0; i  <  s.length(); i++) {
      char c = s.charAt(i);
      if (Character.isDigit(c)) {
        currNum = currNum * 10 + Character.getNumericValue(c);
      } 
      if ((!Character.isDigit(c) && !Character.isWhitespace(c)) || i == s.length() - 1) {
        if (operation == '-' || operation == '+') {
          result += prevNum;
          prevNum = operation == '+' ? currNum : -currNum;
        } else if (operation == '*') {
          prevNum = prevNum * currNum;
        } else {
          prevNum = prevNum / currNum;
        }
        operation = c;
        currNum = 0;
      }
    }
    result += prevNum;
    return result;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = " 3/2 "

Output

x
+
cmd
1

#4 Code Example with Javascript Programming

Code - Javascript Programming

start coding...
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = " 3/2 "

Output

x
+
cmd
1

#5 Code Example with Python Programming

Code - Python Programming


const calculate = function(s) {
  const stk = []
  let op = '+', num = 0
  s = s.trim()
  const isDigit = ch => ch >= '0' && ch <= '9'
  for(let i = 0, n = s.length; i  <  n; i++) {
    const ch = s[i]
    if(ch === ' ') continue
    if(isDigit(ch)) {
      num = (+num) * 10 + (+ch)
    } 
    if(!isDigit(ch) || i === n - 1) {
      if(op === '-') stk.push(-num)
      else if(op === '+') stk.push(num)
      else if(op === '*') stk.push(stk.pop() * num)
      else if(op === '/') stk.push(~~(stk.pop() / num))
      
      op = ch
      num = 0
    }
  }
  let res = 0  
  for(const e of stk) res += e

  return res
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = " 3+5 / 2 "

Output

x
+
cmd
5

#6 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;

namespace LeetCode
{
    public class _0227_BasicCalculatorII
    {
        public int Calculate(string s)
        {
            char sign = '+';
            var nums = new Stack < int>();
            int cur = 0;

            for (int i = 0; i  < = s.Length; i++)
            {
                if (i < s.Length && s[i] >= '0' && s[i] <= '9')
                    cur = cur * 10 + s[i] - '0';
                else if (i == s.Length || s[i] != ' ')
                {
                    if (sign == '+') nums.Push(cur);
                    else if (sign == '-') nums.Push(-cur);
                    else if (sign == '*')
                    {
                        var pre = nums.Pop();
                        nums.Push(pre * cur);
                    }
                    else if (sign == '/')
                    {
                        var pre = nums.Pop();
                        nums.Push(pre / cur);
                    }

                    if (i  <  s.Length)
                    {
                        cur = 0;
                        sign = s[i];
                    }
                }
            }

            var res = 0;
            while (nums.Count > 0)
                res += nums.Pop();
            return res;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = " 3+5 / 2 "

Output

x
+
cmd
5
Advertisements

Demonstration


Previous
#226 Leetcode Invert Binary Tree Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#228 Leetcode Summary Ranges Solution in C, C++, Java, JavaScript, Python, C# Leetcode