题目描述
解题思路
- 利用STL中 stack 的用法。
- 当前读入字符为“+”,push下一数字进栈
- 当前读入字符为“-”,push下一数字的负值进栈,此处经过验证是正确的
- 当前读入字符为“*”,pop当前栈顶值a,push a 与下一数字的乘积进栈
- 当前读入字符为“/”,pop当前栈顶值a,push a 除下一数字进栈
直至最终将栈中所有元素相加即可。
- 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");
}
}