二十四点

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include <stack>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
stack<int> num;
stack<char>sign;
int n;
char str[10];
int main()
{
    fstream file;
    file.open("C:\\Users\\在下帅锋\\Desktop\\1.txt");
    while(!file)
    {
        cerr<<"File open fail!"<<endl;
        exit(0);
    }
    file>>n;
    for(int i=0; i<n; i++)
    {
        file>>str;

        while(!num.empty())
            num.pop();//清空栈
        while(!sign.empty())
            sign.pop();

        int j=0;
        while(j<strlen(str))
        {

            if(str[j]>'0'&&str[j]<='9')
            {
                num.push(str[j]-'0');//将数字压栈
            }
            else
            {
                if(str[j]=='+')
                    sign.push(str[j]);
                else if(str[j]=='-')//把减法变成加法
                {
                    num.push((str[j+1]-'0')*(-1));
                    sign.push('+');
                    j++;
                }
                else if(str[j]=='x')//直接计算乘法,并将结果压栈
                {
                    int temp=num.top();
                    num.pop();
                    num.push(temp*(str[j+1]-'0'));
                    j++;
                }
                else if(str[j]=='/')//直接计算除法,并将结果压栈
                {
                    int temp=num.top();
                    num.pop();
                    num.push(temp/(str[j+1]-'0'));
                    j++;
                }
            }
            j++;

        }

        while(!sign.empty())//计算剩余加法
        {
            int temp =num.top();
            num.pop();
            int test=num.top();
            num.pop();
            sign.pop();
            num.push(temp+test);
        }
        int temp=num.top();
        if(temp==24)
            cout<<"Yes!"<<endl;
        else
        {
            cout<<"No!"<<endl;
        }

    }
    file.close();
}

在这里插入图片描述
数据:

  • 10
    9+3+4x3
    5+4x5x5
    7-9-9+8
    5x6/5x4
    3+5+7+9
    1x1+9-9
    1x9-5/9
    8/5+6x9
    6x7-3x6
    6x4+4/5
    思路:压栈,弹栈。两个栈,一存数字,一存符号。遇+压,遇-变加再压,遇*/计算后将结果压栈。最后再弹栈,相加结果再入栈,栈中数字即为最后的结果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值