当前位置:   article > 正文

力扣-面试题 16.26题 计算器(C++)- 栈_力扣计算器题

力扣计算器题

题目链接:https://leetcode-cn.com/problems/calculator-lcci/
题目如下:
在这里插入图片描述

class Solution {
public:
    int calculate(string s) {
        stack<int> stk1;//存放数字
        stack<char> stk2;//存放运算符
        long long sum=0;//计算运算符之前的数
        bool flag=false;//以防数字为0的情形,如0+0

        for(auto e:s){
            if(isdigit(e)) {//判断是否为为数字
                sum=sum*10+e-'0';
                flag=true;
            }else if(e==' ') {
                continue;
            }else {//为运算符
                stk1.push(sum);sum=0;flag=false;//数字入栈
                if(stk2.size()==0) stk2.push(e);//判断是否已存有运算符
                else {
                    if(judge_priority(e,stk2.top())>0){stk2.push(e);continue;}
                    while(stk2.size()!=0&&judge_priority(e,stk2.top())<=0){//注:同级运算符计算,只能从左往右,不能从右往左
                        int a,b;
                        a=stk1.top();stk1.pop();
                        b=stk1.top();stk1.pop();cout<<a<<','<<b<<endl;
                        char ch=stk2.top();stk2.pop();
                        stk1.push(cal(a,b,ch));                        
                    }
                    stk2.push(e);
                }
            } 
        }
        if(stk2.size()==0) return sum;
        if(flag==true) stk1.push(sum);//放入最后一个数

        //最后的栈中内容计算
        while(stk2.size()!=0){
            int a,b;
            a=stk1.top();stk1.pop();
            b=stk1.top();stk1.pop();
            char e=stk2.top();stk2.pop();
            stk1.push(cal(a,b,e));
        }

        return stk1.top();

    }
    int judge_priority(char a,char b){
        if((a=='*'||a=='/')&&(b=='+'||b=='-')) return 1;//当前运算符比栈顶运算符大
        else if((b=='*'||b=='/')&&(a=='+'||a=='-')) return -1;//当前运算符比栈顶运算符号小
        else return 0;
    }
    int cal(int a,int b,char op){
        switch(op){
                case '*':return b*a;
                case '/':return b/a;
                case '+':return b+a;
                case '-':return b-a;
        }
        return 0;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/848218
推荐阅读
相关标签
  

闽ICP备14008679号