首页 > 其他 > 详细

CCF 20190302 二十四点

时间:2020-04-10 12:41:20      阅读:142      评论:0      收藏:0      [点我收藏+]

思路:表达式求值问题。遇到数字,加入数字栈中;遇到+,将加数加入到栈中;遇到-,将减数的相反数加入栈中;遇到x,让栈顶的数字出栈,与乘数相乘,将结果加入栈中;遇到/,让栈顶的数字出栈,与除数相除,将结果加入栈中;最后将栈中所有元素相加即可。
注意:输入的表达式存储在string中,故要的到数字应用str[i]-‘0‘。

代码实现:

#include<iostream>
#include<string>
#include<stack>

using namespace std;
stack<int> s;
int main(){
    int n;
    cin>>n;
    string str;
    for(int i = 0; i < n; i++){
        cin>>str;
        for(int j = 0; j < str.size();j++){
            if(str[j] > ‘0‘ && str[j] <= ‘9‘){
                s.push(str[j]-‘0‘);
            }
            else if(str[j] == ‘+‘){
                s.push(str[++j]-‘0‘);
            }
            else if(str[j] == ‘-‘){
                s.push(‘0‘ - str[++j]);
            }
            else if(str[j] == ‘x‘){
                int tmp = s.top();
                s.pop();
                s.push(tmp*(str[++j]-‘0‘));
            }
            else if(str[j] == ‘/‘){
                int tmp = s.top();
                s.pop();
                s.push(tmp/(str[++j]-‘0‘));
            }
        }
        int sum = 0;
        while(!s.empty()){
            sum += s.top();
            s.pop();
        }
//        cout<<sum<<endl;
        if(sum == 24){
            cout<<"Yes"<<endl;
        }
        else{
            cout<<"No"<<endl;
        }
    }
    return 0;
}


CCF 20190302 二十四点

原文:https://www.cnblogs.com/blink-cz/p/12672401.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!