CCF 二十四点

原题链接

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

int main() {
    int n,ans,a,b;
    char ch;
    char s[10];
    stack<char>st,st2;
    stack<int>temp,temp2;
    cin >> n;
    for(int i=0; i<n; i++) {
        cin >> s;
        while(!st.empty()) st.pop();
        while(!temp.empty()) temp.pop();
        while(!st2.empty()) st2.pop();
        while(!temp2.empty()) temp2.pop();
        for(int j=0; j<7; j++) {
            if(s[j]<='9' && s[j]>='0')temp.push(s[j]-'0');//数字和+-全部入栈
            else if(s[j]=='+' || s[j]=='-') {
                st.push(s[j]);
            } else if(s[j]=='x' || s[j]=='/') {    // 乘除直接计算
                a = temp.top();
                temp.pop();
                b = s[j+1] - '0';
                temp.push(s[j]=='x' ? a*b : a/b);
                j++;    // 在计算乘除的时候,已经把下一个数字用了
            }
        }
        // 目的是把操作顺序改过来
        while(!st.empty()) {
            st2.push(st.top());
            st.pop();
        }
        while(!temp.empty()) {
            temp2.push(temp.top());
            temp.pop();
        }
        while(!st2.empty()) {
            ch = st2.top();
            st2.pop();
            a = temp2.top();
            temp2.pop();
            b = temp2.top();
            temp2.pop();
            temp2.push(ch == '+' ? a + b : a-b);
        }
        ans = temp2.top();
        if(ans == 24) cout<< "Yes" <<endl;
        else cout<< "No"<<endl;
    } 
    return 0;
}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值