201903-2二十四点

#include<iostream>
#include<stack>
#include<ctype.h>
#include<string>
using namespace std;
struct oprt
{
    char opr;
    int clas;//运算符等级
};
oprt op[5] = { {'#',0}, {'+',1},{'-',1},{'x',3},{'/',3} };
int judge(char c)
{
    for (int i = 0; i < 5; i++)
    {
        if (op[i].opr == c)
            return op[i].clas;
    }
    return -1;
}
int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        string s;
        cin >> s;
        stack<int> nu;
        stack<char> opr;
        opr.push('#');
        for (int j = 0; j < 7; j++)//将计算表达式压入栈中,要求已有符号若大于待入符号,则先运算已有符号即可,否则压入
        {
            if (isdigit(s[j]))
            {
                nu.push(s[j]-'0');
            }
            else
            {
                if (judge(s[j]) > judge(opr.top()))
                {
                    opr.push(s[j]);
                }
                else
                {
                    char ct = opr.top();
                    opr.pop();
                    int t2 = nu.top();
                    nu.pop();
                    int t1 = nu.top();
                    nu.pop();
                    switch (ct)
                    {
                    case '+':nu.push(t1 + t2); break;
                    case '-':nu.push(t1 - t2); break;
                    case 'x':nu.push(t1 * t2); break;
                    case '/':nu.push(t1 / t2); break;
                    }
                    opr.push(s[j]);
                }
            }
        }
        //最终形成的符号栈总下到上等级提高
        while (nu.size() > 1)
        {
            char ct = opr.top();
            opr.pop();
            int t2 = nu.top();
            nu.pop();
            int t1 = nu.top();
            nu.pop();
            switch (ct)
            {
            case '+':nu.push(t1 + t2); break;
            case '-':nu.push(t1 - t2); break;
            case 'x':nu.push(t1 * t2); break;
            case '/':nu.push(t1 / t2); break;
            }
        }
        if (nu.top() == 24)
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/WuDie/p/11327889.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值