878885. Calculator

Easy

Calculator

Summary

This problem involves creating a simple calculator that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division. The calculator should be able to handle multiple operations in sequence, allowing users to input expressions like "2+3*4" or "10-5/2". This problem requires an understanding of control flow and operator precedence.

Detailed Explanation

To solve this problem, we can use a stack-based approach. We'll define a function calculate that takes a string expression as input and returns the result of evaluating the expression. Here's a step-by-step breakdown of the solution:

  1. Tokenization: Split the input expression into individual tokens (operators and operands). For example, "2+34" would become ["2", "+", "3", "", "4"].
  2. Operator precedence: Determine the order in which operators should be applied. In this case, we'll follow the standard operator precedence rules: multiplication and division have higher precedence than addition and subtraction.
  3. Evaluation: Evaluate each token as follows:
    • Operands (numbers): Store them in a stack.
    • Operators (+, -, *, /):
      • If the top of the stack is an operand, push the new operand onto the stack.
      • If the top of the stack is an operator, pop the top two operands from the stack, apply the operation, and push the result back onto the stack.
  4. Final result: The final result is the single value left on the stack after all tokens have been processed.

Time complexity: O(n), where n is the length of the input expression. Space complexity: O(n), as we need to store the tokens in a stack.

Optimized Solutions

Java

View on GeeksforGeeks
public class Calculator {
    public static double calculate(String expression) {
        // Tokenization and operator precedence not shown for brevity
        Stack<Double> stack = new Stack<>();
        for (String token : tokens) {
            if (isOperator(token)) {
                // Operator processing logic goes here
            } else {
                stack.push(Double.parseDouble(token));
            }
        }
        return stack.pop();
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.