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

代码:

扫描二维码关注公众号,回复: 6686630 查看本文章
#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;
}

猜你喜欢

转载自www.cnblogs.com/ellen-mylife/p/11110127.html