Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Stack & Queue

Basic Calculator II

Medium · Stack & Queue · Asked at Meta, Amazon, Microsoft, Apple

Evaluate an expression containing non-negative integers, the operators + - * / and spaces (no parentheses). * and / bind tighter than + and -, operators of the same level are applied left to right, and division truncates toward zero. Print the result.

Input

A single line with the expression.

Output

The value of the expression.

Constraints

Keep a stack of terms. Read a number; based on the operator before it, push +num, push −num, or replace the top with top × num or top / num. The answer is the sum of the stack — or keep just a running total and the last term.

Example 1

Input

3+2*2

Output

7

Example 2

Input

 3/2 

Output

1

Example 3

Input

 3+5 / 2 

Output

5

Hints

  1. Without parentheses, the expression is a sum of terms; each term is a product/quotient chain.
  2. When you read a number, look at the operator before it.
  3. + and − start a new term; * and / change the last term.

Approach

Walk through the string, skipping spaces, and keep the total of finished terms plus the current term last. When a number is complete, apply the previous operator: + → total += last, last = num; − → total += last, last = −num; * → last *= num; / → last /= num (C++/Java integer division already truncates toward zero; in Python use int(last / num) or an explicit sign fix). At the end, answer = total + last.

Complexity: O(n) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    long long total = 0, last = 0, num = 0;
    char op = '+';
    for (size_t i = 0; i <= s.size(); i++) {
        char c = i < s.size() ? s[i] : '+';
        if (c == ' ' || c == '\r') continue;
        if (isdigit((unsigned char) c)) {
            num = num * 10 + (c - '0');
            continue;
        }
        if (op == '+') {
            total += last;
            last = num;
        } else if (op == '-') {
            total += last;
            last = -num;
        } else if (op == '*') last *= num;
        else last /= num;
        op = c;
        num = 0;
    }
    cout << total + last << "\n";
    return 0;
}

Python solution

import sys

s = sys.stdin.readline().strip() + "+"
total = last = num = 0
op = "+"
for c in s:
    if c == " ":
        continue
    if c.isdigit():
        num = num * 10 + ord(c) - 48
        continue
    if op == "+":
        total += last
        last = num
    elif op == "-":
        total += last
        last = -num
    elif op == "*":
        last *= num
    else:
        q = abs(last) // num
        last = q if last >= 0 else -q  # truncate toward zero
    op = c
    num = 0
print(total + last)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
        long total = 0, last = 0, num = 0;
        char op = '+';
        for (int i = 0; i <= s.length(); i++) {
            char c = i < s.length() ? s.charAt(i) : '+';
            if (c == ' ') continue;
            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
                continue;
            }
            if (op == '+') {
                total += last;
                last = num;
            } else if (op == '-') {
                total += last;
                last = -num;
            } else if (op == '*') last *= num;
            else last /= num;
            op = c;
            num = 0;
        }
        System.out.println(total + last);
    }
}

Solve Basic Calculator II online · All practice problems