面试题 16.26. 计算器

  1. 面试题 16.26. 计算器
  2. 题解

面试题 16.26. 计算器

难度中等22收藏分享切换为英文接收动态反馈

给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。

表达式仅包含非负整数,+-*/ 四种运算符和空格 。 整数除法仅保留整数部分。

示例 1:

输入: "3+2*2"
输出: 7

示例 2:

输入: " 3/2 "
输出: 1

示例 3:

输入: " 3+5 / 2 "
输出: 5

说明:

  • 你可以假设所给定的表达式都是有效的。
  • 不要使用内置的库函数 eval

通过次数6,509

提交次数17,412

题解

class Solution:
    def calculate(self, s: str) -> int:
        s = list(s)
        stack = []
        num = 0
        opt = "+" # 第一个数可以看成是 [0] + num , 也就是第一个数一定是正数
        opreate = ["+", "-", "*", "/"]
        for i in range( len(s)):
            # 注意是弹栈头的方式
            ch = s.pop(0)
            # 如果是数字则继续加, 可能有多位
            if ch.isdigit():
                num = num * 10 + int(ch)
            # 如果题目中带() ,则 对()中的表达式进行递归操作
            if ch == '(':
                self.calculate(s)
            if ch in opreate or not s or ch == ')':
                # opt保存的是上一个非数字的符号,
                # stack.pop() 保存的是 上一个非数组符号的左边的数
                # num 保存的是上一个非数组符号的右边的数
                # 最后计算他们2个 值
                if opt == "+":
                    stack.append( num)
                if opt == "-":
                    stack.append(-num)
                if opt == '*':
                    stack.append( stack.pop() * num)
                if opt == "/":
                    stack.append( int ( stack.pop() / num)) 
                # 计算完之后,再讲计算式保存为当前的计算符
                opt = ch 
                # 将num清0
                num = 0;
            if ch == ')':
                break
        return sum(stack)
class Solution {
    public int calculate(String s) {
        s = s.trim();
        char[] str = s.toCharArray();
        int num = 0;
        Stack<Integer> stack = new Stack();
        stack.add(0);
        //char[] operate = {'+','-','*','/'};
        char opt = '+';
        int res = 0;
        for (int i = 0; i < str.length; i++) {
            char pop = str[i];
            if (pop == ' ') continue;
            if (Character.isDigit(pop)) {
                num = num * 10 + (pop - '0');
            }
            System.out.println(num);
            if ((!Character.isDigit(pop) && pop != ' ') || i == str.length -1 ) { // 如果pop 不为数字和空, 或者已经遍历到最后面了
                if (opt == '+') {
                    stack.add( num);
                }else if (opt == '*') {
                    stack.add(stack.pop() * num);
                }else if (opt == '-') {
                    stack.add(-num);
                }else if (opt == '/') {
                    stack.add(stack.pop() / num);
                }
                opt = pop;
                num = 0;
            }

        }
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 mym_74@163.com