Code Logo

Basic Calculator II

Published at23 Jul 2026
Medium 0 views
Like0

You are given a string containing a valid arithmetic expression with integers and the operators +, -, *, /. There are no parentheses. Evaluate the expression and return the result.

Operator precedence matters: multiplication and division must be evaluated before addition and subtraction. A stack makes this easy. Iterate through the string, parse numbers, and when you see a + or -, push the number (positive or negative). When you see * or /, pop the last number, compute the result, and push it back. At the end, sum all values on the stack.

Integer division should truncate toward zero. The expression is always valid.

Example Input & Output

Example 1
Input
3+5/2
Output
5
Explanation

5/2=2, then 3+2=5

Example 2
Input
3+2*2
Output
7
Explanation

2*2=4, then 3+4=7

Example 3
Input
3-5*2+8/4
Output
-5
Explanation

-5*2=-10, then 3-10=-7, then -7+2=-5

Example 4
Input
3/2
Output
1
Explanation

Integer division truncates toward zero: 3/2=1

Algorithm Flow

Recommendation Algorithm Flow for Basic Calculator II
Recommendation Algorithm Flow for Basic Calculator II

Solution Approach

Iterate through the string character by character, building the current number. When you encounter an operator or reach the end, check the previous operator. If it was + or -, push the current number (with sign) onto the stack. If it was * or /, pop the last number, compute the result, and push it back. At the end, sum all values on the stack.

function solution(s) {
  var stack = []
  var num = 0
  var sign = '+'
  for (var i = 0; i < s.length; i++) {
    var ch = s[i]
    if (ch >= '0' && ch <= '9') num = num * 10 + Number(ch)
    if (ch === '+' || ch === '-' || ch === '*' || ch === '/' || i === s.length - 1) {
      if (sign === '+') stack.push(num)
      else if (sign === '-') stack.push(-num)
      else if (sign === '*') stack.push(stack.pop() * num)
      else if (sign === '/') stack.push(Math.trunc(stack.pop() / num))
      num = 0; sign = ch
    }
  }
  var sum = 0
  while (stack.length) sum += stack.pop()
  return sum
}

Time complexity is O(n). Space complexity is O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(String s) {
        Stack<Integer> stack = new Stack<>();
        int num = 0; char sign = '+';
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch >= '0' && ch <= '9') num = num * 10 + (ch - '0');
            if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || i == s.length() - 1) {
                if (sign == '+') stack.push(num); else if (sign == '-') stack.push(-num);
                else if (sign == '*') stack.push(stack.pop() * num);
                else if (sign == '/') stack.push(stack.pop() / num);
                num = 0; sign = ch;
            }
        }
        int sum = 0; while (!stack.isEmpty()) sum += stack.pop();
        return sum;
    }
}