LeetCode——227. Basic Calculator II

Title description:

Give you a string expression s, please implement a basic calculator to calculate and return its value.
Integer division only retains the integer part.

prompt:

  1. 1 <= s.length <= 3 * 105
  2. s is composed of integers and operators ('+','-','*','/'), separated by some spaces
  3. s represents a valid expression, all integers in the expression are non-negative integers and are in the range [0, 231-1]
  4. The question data guarantees that the answer is a 32-bit integer

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

code show as below:

class Solution {
    
    
    public int calculate(String str) {
    
    
        String s = str.trim();
        int n = s.length();
        Stack<Integer> stack = new Stack<>();
        int num = 0;
        char sign = '+';
        for (int i = 0; i < n; i++) {
    
    
            char ch = s.charAt(i);
            if (Character.isSpaceChar(ch)) {
    
    
                continue;
            }
            if (Character.isDigit(ch)) {
    
    
                num = 10 * num + (ch - '0');
            }
            if (!Character.isDigit(ch) || i == n - 1) {
    
    
                if (sign == '+') {
    
    
                    stack.push(num);
                } else if (sign == '-') {
    
    
                    stack.push(-num);
                } else if (sign == '*') {
    
    
                    stack.push(stack.pop() * num);
                } else if (sign == '/') {
    
    
                    if (num != 0) {
    
    
                        stack.push((int) (stack.pop() / num));
                    }
                }
                sign = ch;
                num = 0;
            }
        }
        int ans = 0;
        while (!stack.isEmpty()) {
    
    
            ans += stack.pop();
        }
        return ans;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114653148