牛客 - 表达式求值 (栈的应用)

题目:表达式求值

Description

给定一个只包含加法和乘法的算术表达式,请你编程计算表达式的值。

Input

输入仅有一行,为需要你计算的表达式,表达式中只包含数字、加法运算符“+”和乘法运算符“*”,且没有括号。
所有参与运算的数字均为 0 到 231-1 之间的整数。
输入数据保证这一行只有0~9、+、*这12种字符。

Output

输出只有一行,包含一个整数,表示这个表达式的值。注意:当答案长度多于4位时,请只输出最后4位,前导0不输出。

Sample

示例1

输入
1+1*3+4
输出
8
说明
计算的结果为8,直接输出8。

示例2

输入
1+1000000003*1
输出
4
说明
计算的结果为1000000004,输出后4位,即4。

Solution

维护两个栈!一个存放数字,一个存放运算符!模拟计算过程!代码写得很丑

AC Code
#include<bits/stdc++.h>
using namespace std;
int mod = 10000;

long long change(string s) {
    
    //字符串转换成数字
    long long ans = 0;
    for (char x : s) {
    
    
        ans = ans * 10 + (x - '0');
        ans %= mod;
    }
    return ans;
}
bool compare(char a, char b) {
    
    //a在b之后 判断优先级
    if (a == '+') {
    
    
        return 0;
    }
    else if (a == '*') {
    
    
        return 1;
    }
}
int evalRPN(vector<string>& tokens) {
    
    
    stack<long long> shu;
    stack<char> fu;
    for (int i = 0;i<tokens.size();i++) {
    
    
        string x = tokens[i];
        if (x >= "0") {
    
    
            shu.push(change(x));
        }
        else if (x < "0") {
    
    
            if (fu.size() == 0) fu.push(x[0]);
            else {
    
    
                char f = fu.top();
                bool v = compare(x[0], f);
                if (v) {
    
    
                    fu.push(x[0]);
                }
                else{
    
    
                    char c = fu.top();
                    fu.pop();
                    int b = shu.top();
                    shu.pop();
                    int a = shu.top();
                    shu.pop();
                    switch (c) {
    
    
                    case '+':shu.push((a + b)%mod); break;
                    case '*':shu.push((a * b) % mod); break;
                    }
                    i--;
                }
            }
        }
    }
    while (fu.size()) {
    
    
        char c = fu.top();
        fu.pop();
        int b = shu.top();
        shu.pop();
        int a = shu.top();
        shu.pop();
        switch (c) {
    
    
            case '+':shu.push((a + b) % mod); break;
            case '*':shu.push((a * b) % mod); break;
        }
    }
    return shu.top();
}
int main() {
    
    
    string str;
    cin >> str;
    vector<string> s;
    string f;
    for (char x : str) {
    
    
        if (x < '0') {
    
    
            s.push_back(f);
            f = "";
            f += x;
            s.push_back(f);
            f = "";
        }
        else {
    
    
            f += x;
        }
    }
    s.push_back(f);
    cout << evalRPN(s);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/buibuilili/article/details/109037201