ccf——20190302二十四点

参考

 

这道题是四则运算,我们用栈来解决它

使用c++中的模板类stack

#include<stack>         //头文件

stack <int> num;      //定义一个int型栈

num.push();            //在栈顶上堆进一个元素

num.pop();             //删除掉栈顶上的元素

num.top();             //返回栈顶的元素,并不会删除  

num.empty();           //返回栈是否为空

num.size();            //返回当前栈中元素的个数  

1.当字符为数字时,存入num栈中

2.当字符是“+”时,存入sign栈中

3.当字符是“-”时,因为减一个数等于加一个数的相反数,所以将下一个字符取反存入num栈,sign栈存入“+”

4.当字符是“X”时,取当前字符q和下一个字符p,将q*p存入num

5.当字符是“/”时,取当前字符q和下一个字符p,将q/p存入num

代码:

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
int n;
char str[10];
stack<int> num;
stack<char> sign;
int main()
{
    scanf("%d",&n);
    getchar();
    while(!num.empty()) num.pop();
    while(!sign.empty()) sign.pop();
    for(int i=0;i<n;i++)
    {
        gets(str);
        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('+');
            }
            else if(str[j]=='-')
            {
                j++;
                num.push((-1)*(str[j]-'0'));
                sign.push('+');
            }
            else if(str[j]=='x')
            {
                int q=num.top();
                num.pop();
                j++;
                int p=str[j]-'0';
                num.push(q*p);
            }
            else if(str[j]=='/')
            {
                int q=num.top();
                num.pop();
                j++;
                int p=str[j]-'0';
                num.push(q/p);
            }
            j++;
        }
        while(!sign.empty())
        {
            int q=num.top();
            num.pop();
            int p=num.top();
            num.pop();
            sign.pop();
            num.push(q+p);
        }
        //printf("%d\n",num.top());
            if(num.top()==24) printf("Yes\n");
        else printf("No\n");
    }
    
    
    return 0;
}

 

转载于:https://www.cnblogs.com/ellen-mylife/p/11110127.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值