CSP-20190302 | stack

CSP-20190302 | stack

题目描述

在这里插入图片描述

在这里插入图片描述

解题思路

  1. 利用STL中 stack 的用法。
  • 当前读入字符为“+”,push下一数字进栈
  • 当前读入字符为“-”,push下一数字的负值进栈,此处经过验证是正确的
  • 当前读入字符为“*”,pop当前栈顶值a,push a 与下一数字的乘积进栈
  • 当前读入字符为“/”,pop当前栈顶值a,push a 除下一数字进栈

直至最终将栈中所有元素相加即可。

  1. DEV c++中的调试添加变量时不支持直接查看STL容器名来获取相关信息,只能通过添加类似于st.top()、st.size()等信息来查看(st为stack变量)

代码

#include<bits/stdc++.h>
#include<algorithm>
using namespace std;

stack<int> st;
char str[200][10];
int res[200]={0};

int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%s",str[i]);
		}
	for(int i=1;i<=n;i++)
	{ 
		while(st.empty()!=true)
		{
			st.pop();
		}
		for(int j=0;j<=6;j++)
		{
			if(isdigit(str[i][j]))
			{
				st.push(str[i][j]-'0');
			}
			else 
			{
				if(str[i][j]=='+') 
				{
					j++; 
					st.push(str[i][j]-'0');
				}
				else if(str[i][j]=='-')
				{
					j++;
					st.push(-(str[i][j]-'0'));
				}
				else if(str[i][j]=='x')
				{
					int temp=st.top();
					st.pop();
					j++;
					st.push(temp*(str[i][j]-'0'));
				}
				else if(str[i][j]=='/')
				{
					int temp=st.top();
					st.pop();
					j++;
					st.push(temp/(str[i][j]-'0'));
				}
			}
			
			
		}
		while(st.size()>=1)
			{
				res[i]+=st.top();
				st.pop();
			}
	}
	
	for(int i=1;i<=n;i++)
	{
		if(res[i]==24) printf("Yes\n");
		else printf("No\n");
	}
	
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值