Basic Calculator II LeetCode Solution

Last updated on July 15th, 2024 at 01:25 am

Here, We see Basic Calculator II LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Topics

String

Companies

Airbnb

Level of Question

Medium

Basic Calculator II LeetCode Solution

Basic Calculator II LeetCode Solution

Problem Statement

Given a string 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].

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

1. Basic Calculator II Leetcode Solution C++

class Solution {
public:
    int calculate(string s) {
    istringstream in('+' + s + '+');
    long long total = 0, term = 0, n;
    char op;
    while (in >> op) {
        if (op == '+' or op == '-') {
            total += term;
            in >> term;
            term *= 44 - op;
        } else {
            in >> n;
            if (op == '*')
                term *= n;
            else
                term /= n;
        }
    }
    return total;
 }
};

1.1 Explanation

  1. Initialization: The input string s is prefixed and suffixed with ‘+’ to handle edge cases.
  2. Reading Characters: The istringstream reads characters one by one.
  3. Handling ‘+’ and ‘-‘: If the operator is ‘+’ or ‘-‘, the previous term is added to total. The next term is read and multiplied by 1 or -1 based on the operator.
  4. Handling ‘*’ and ‘/’: The term is multiplied or divided by the next number.
  5. Final Sum: The total sum is returned.

1.2 Time Complexity

  • O(n).

1.3 Space Complexity

  • O(1).

2. Basic Calculator II Leetcode Solution Java

class Solution {
    public int calculate(String s) {
        if (s == null || s.length() == 0) return 0;
        int num = 0, tmp = 0, res = 0;
        char op = '+';
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                tmp = tmp*10 + c - '0';
            } else if (c != ' ') {
				//process the numerical value of string so far; based on what 'op' we have before it
                num = cal(num, tmp, op);
                if (c == '+' || c == '-') {
                    res += num;
                    num = 0;
                }
				// reset
                tmp = 0;
                op = c;
            }
        }
        return res + cal(num, tmp, op);
    }
    private int cal(int num, int tmp, char op) {
        if (op == '+') return num + tmp;
        else if (op == '-') return num - tmp;
        else if (op == '*') return num * tmp;
        else    return num / tmp;
    }
}

2.1 Explanation

  1. Initialization: Initialize num, tmp, res, and op to handle the current number, temporary number, result, and current operator respectively.
  2. Processing Characters: Convert characters to numbers if they are digits.
  3. Handling Operators: When encountering an operator, compute the result so far and reset temporary values.
  4. Final Calculation: Add the last computed value to the result and return it.

2.2 Time Complexity

  • O(n).

2.3 Space Complexity

  • O(1).

3. Basic Calculator II Leetcode Solution JavaScript

var calculate = function(s) {
  let stack = [];
  let num = '';
  let sign = null
  for(let i = 0; i <= s.length; i++){    
    const curr = s[i];
    if(curr === ' ') continue;
    if(!isNaN(curr)) num+=curr;
    if(isNaN(curr)){
      num = Number(num)
      switch(sign){
        case '+':
        case null:
          stack.push(num)
          break;
        case '-':
          stack.push(-num)
          break; 
        case '*':
          stack.push(stack.pop()*num)
          break;
        case '/':
          stack.push(parseInt(stack.pop()/num, 10))
          break;           
      }
      sign = curr;
      num = '';
    }
  }
  return stack.reduce((a,b)=>{
    return a+b
  },0)
};

3.1 Explanation

  1. Initialization: Initialize stack, num, and sign.
  2. Processing Characters: Convert characters to numbers if they are digits.
  3. Handling Operators: Push or compute based on the operator.
  4. Final Sum: Reduce the stack to compute the final sum.

3.2 Time Complexity

  • O(n).

3.3 Space Complexity

  • O(n).

4. Basic Calculator II Leetcode Solution Python

class Solution:
    def calculate(self, s: str) -> int:
        num = 0
        res = 0
        pre_op = '+'
        s+='+'
        stack = []
        for c in s:
            if c.isdigit():
                num = num*10 + int(c)
            elif c == ' ':
                    pass
            else:
                if pre_op == '+':
                    stack.append(num)
                elif pre_op == '-':
                    stack.append(-num)
                elif pre_op == '*':
                    operant = stack.pop()
                    stack.append((operant*num))
                elif pre_op == '/':
                    operant = stack.pop()
                    stack.append(math.trunc(operant/num))
                num = 0
                pre_op = c
        return sum(stack)

4.1 Explanation

  1. Initialization: Initialize num, res, pre_op, and stack.
  2. Processing Characters: Convert characters to numbers if they are digits.
  3. Handling Operators: Push or compute based on the operator.
  4. Final Sum: Sum up the values in the stack and return the result.

4.2 Time Complexity

  • O(n).

4.3 Space Complexity

  • O(n).
Scroll to Top