题解 | #计算表达式#

计算表达式

https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

/*
 * 思路:识别数字num并压栈,当识别到运算符时看运算符栈的栈顶运算符的优先级,只有当栈顶运算符优先级低于要压入的运算符时
 * 才能将此运算符压栈。否则弹出栈顶运算符,并和数字栈的前两个运算符进行计算并将结果压栈。不断重复此操作即可。
 */
#include "stdio.h"
#include "string"
#include "stack"
#include "map"
using namespace std;
char buf[200];string str;
stack<double> numStack;stack<char> operStack;
map<char,int> myMap = {{'+',1},{'-',1},{'*',2},{'/',2},{'#',0}};
//myMap为运算符优先级
int num = 0;//num为识别的数字,sum为计算的和
double calculate(double num1,double num2,char oper){//弹栈时的计算
    switch (oper) {
        case '+':
            return (num1+num2)*1.0;
        case '-':
            return (num1-num2)*1.0;
        case '*':
            return num1*num2*1.0;
        case '/':
            return 1.0*num1/num2;
        default:
            return -100.0;
    }
}

void operInStack(char oper){//字符串入栈
    numStack.push(num);num = 0;//前面的数字num先入栈
    if (operStack.empty()){//符号栈为空直接压栈
        operStack.push(oper);
    } else{//栈顶的运算符优先级低,压栈,否则弹栈计算sum。再次判断,重复此次循环
        while (!operStack.empty() && myMap[operStack.top()] >= myMap[oper]){
            char oper2;//栈里弹出的运算符
            oper2 = operStack.top();
            operStack.pop();
            double num2 = numStack.top();numStack.pop();
            double num1 = numStack.top();numStack.pop();
            double sum = calculate(num1,num2,oper2);
            numStack.push(sum);
        }
        operStack.push(oper);
    }
}

int main(){
    while (scanf("%s",buf)!=EOF){
        str = buf;num = 0;
        for (int i = 0; i < str.size(); ++i) {
            if (buf[i] >= '0' && buf[i] <= '9'){
                num = num*10 + buf[i] - '0';//识别数字
                if (i == str.size()-1)
                    operInStack('#');
            } else if (buf[i] == '+' || buf[i] == '-' ||
                       buf[i] == '*' || buf[i] == '/'){//为运算符时
                char oper = buf[i];
                operInStack(oper);
            }
        }
        int end = numStack.top();
        printf("%d\n",end);
        numStack.pop();operStack.pop();
    }
}

全部评论

相关推荐

吃不饱的肱二头肌很想退休:tnnd 我以为选妹子呢,亏我兴高采烈的冲进来😠
投递快手等公司10个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务