Basic Calculator Ii

Solution For Basic Calculator Ii

Problem Statement:

Given a string s which represents an expression, evaluate this expression and return its value.

The expression is composed of several terms separated by the + or – operator. Each term is either an integer or a variable.

To evaluate the expression, replace each variable with its integer value and perform the specified arithmetic operation.

The expression contains only lowercase English letters, +, -, *, / operators, digits, and whitespace ‘ ‘.

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

Solution:

To solve this problem, we can use the concept of a stack. We can store the operands in the stack and keep track of the previous operator.

Step 1: Initialize the stack and current operand to 0 and the previous operator to ‘+’

Step 2: Remove all the whitespace characters from the string s.

Step 3: Loop through the string s and perform the following operations for each character:

  • If the character is a digit, append it to the current operand.
  • If the character is an operator (+, -, *, /), perform the following operations:
  • Evaluate the previous operation (current operand and previous operator) and push the result to the stack.
  • Update the current operand to 0 and previous operator to the current operator.
  • If the character is a space, skip it.
  • If the character is the last character of the string, evaluate the final operation (current operand and previous operator) and push the result to the stack.

Step 4: Calculate the final result by adding all the elements in the stack.

Code:

class Solution {
public:
int calculate(string s) {
stack st;
char op = ‘+’;
int operand = 0;

    for (int i = 0; i < s.size(); i++) {
        char c = s[i];
        if (isdigit(c)) {
            operand = (operand * 10) + (c - '0');
        }
        if ((!isdigit(c) && c != ' ') || i == s.size() - 1) {
            if (op == '+') {
                st.push(operand);
            } else if (op == '-') {
                st.push(-operand);
            } else if (op == '*') {
                int temp = st.top() * operand;
                st.pop();
                st.push(temp);
            } else if (op == '/') {
                int temp = st.top() / operand;
                st.pop();
                st.push(temp);
            }

            operand = 0;
            op = c;
        }
    }

    int result = 0;
    while (!st.empty()) {
        result += st.top();
        st.pop();
    }

    return result;
}

};

Step by Step Implementation For Basic Calculator Ii

/**
 * Given a string s consists of non-space characters, determine the length of the longest word in s.

Example 1:

Input: "Hello World"
Output: 5

Note:
A word is defined as a character sequence consisting of non-space characters only.
 */

public class Solution {
    public int lengthOfLongestWord(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        String[] arr = s.split(" ");
        int max = 0;
        for (String str : arr) {
            if (str.length() > max) {
                max = str.length();
            }
        }
        return max;
    }
}
class Solution:
    def calculate(self, s: str) -> int:
        # This problem can be solved using a stack
        # We will first convert the string into a list of tokens
        # Then, we will iterate through the list of tokens
        # If the current token is an operator, we will pop the top two elements from the stack, 
        # perform the operation, and push the result back onto the stack
        # If the current token is a number, we will simply push it onto the stack
        # At the end, the stack will contain a single element which is the result of the calculation
        
        # First, we convert the string into a list of tokens
        s = s.replace(" ", "") # remove all whitespace
        tokens = []
        i = 0
        while i < len(s):
            # If the current character is a digit, we will keep reading characters until we reach a non-digit
            if s[i].isdigit():
                num_str = ""
                while i < len(s) and s[i].isdigit():
                    num_str += s[i]
                    i += 1
                tokens.append(int(num_str))
            # If the current character is an operator, we will simply append it to the list of tokens
            else:
                tokens.append(s[i])
                i += 1
        
        # Next, we iterate through the list of tokens
        stack = []
        for token in tokens:
            # If the current token is an operator, we will perform the operation
            if token in ["+", "-", "*", "/"]:
                # We will pop the top two elements from the stack
                num2 = stack.pop()
                num1 = stack.pop()
                # We will then perform the operation and push the result back onto the stack
                if token == "+":
                    stack.append(num1 + num2)
                elif token == "-":
                    stack.append(num1 - num2)
                elif token == "*":
                    stack.append(num1 * num2)
                else:
                    stack.append(num1 // num2)
            # If the current token is a number, we will simply push it onto the stack
            else:
                stack.append(token)
        
        # At the end, the stack will contain a single element which is the result of the calculation
        return stack[0]
var calculate = function(s) {
    let stack = [], num = 0, sign = '+';
    for (let i = 0; i < s.length; i++) {
        if (s[i] === ' ') continue;
        if (Number.isInteger(parseInt(s[i]))) {
            num = num * 10 + parseInt(s[i]);
        } else {
            if (sign === '+') stack.push(num);
            if (sign === '-') stack.push(-num);
            if (sign === '*') stack.push(stack.pop() * num);
            if (sign === '/') stack.push(parseInt(stack.pop() / num));
            sign = s[i];
            num = 0;
        }
    }
    return stack.reduce((a, b) => a + b);
};
class Solution {
public:
    int calculate(string s) {
        int len = s.size(), sign = 1, result = 0;
        stack nums;
        for (int i = 0; i < len; i++) {
            if (isdigit(s[i])) {
                int tmp = s[i] - '0';
                while (i + 1 < len && isdigit(s[i + 1])) {
                    tmp = tmp * 10 + (s[++i] - '0');
                }
                result += sign * tmp;
            } else if (s[i] == '+') {
                sign = 1;
            } else if (s[i] == '-') {
                sign = -1;
            } else if (s[i] == '(') {
                nums.push(result);
                nums.push(sign);
                result = 0;
                sign = 1;
            } else if (s[i] == ')') {
                result = result * nums.top();
                nums.pop();
                result += nums.top();
                nums.pop();
            }
        }
        return result;
    }
};
using System; 

public class Solution {
    public int Calculate(string s) {
        if (s == null || s.Length == 0) return 0;
        int len = s.Length, sign = 1, res = 0;
        Stack stack = new Stack();
        for (int i = 0; i < len; i++) {
            if (Char.IsDigit(s[i])) {
                int sum = s[i] - '0';
                while (i + 1 < len && Char.IsDigit(s[i + 1])) {
                    sum = sum * 10 + s[i + 1] - '0';
                    i++;
                }
                res += sum * sign;
            }
            else if (s[i] == '+')
                sign = 1;
            else if (s[i] == '-')
                sign = -1;
            else if (s[i] == '(') {
                stack.Push(res);
                stack.Push(sign);
                res = 0;
                sign = 1;
            }
            else if (s[i] == ')' && stack.Count != 0) {
                res = res * stack.Pop() + stack.Pop();
            }
        }
        return res;
    }
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]