2019-3-2 二十四点

C++

#include <iostream>
#include <cstdio>
#include <vector>
#include <deque>
#include <stack>
#include <algorithm>
using namespace std;
int main()
{
    int num;
    cin >> num;
    for(int i = 0; i < num; i++){
        getchar();
        deque<int> nums;
        deque<char> operators;
        int first;
        cin >> first;
        nums.push_back(first);
        for(int j = 0; j < 3; j++){
            char c = getchar();
            int x;
            cin >> x;
            if(c=='x'){
                x=nums.back()*x;
                nums.pop_back();
            }else if(c=='/'){
                x=nums.back()/x;
                nums.pop_back();
            }else{
                operators.push_back(c);
            }
            nums.push_back(x);
        }
        while(nums.size()>1){
            int x = nums.front();
            nums.pop_front();
            if(operators.front() == '+')
                x += nums.front();
            else
                x -= nums.front();
            nums.pop_front();
            operators.pop_front();
            nums.push_front(x);
        }
        if(nums.front()==24)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;

    }


    return 0;
}

Java

import java.util.Scanner;
import java.util.Stack;

public class Main {

	public static void main(String[] args){
        int num=0;
        Scanner sc = new Scanner(System.in);
        num = sc.nextInt();
        for(int i = 0; i < num; i++){
 
            Stack<Integer> nums=new Stack<Integer>();
            Stack<Character> operators=new Stack<Character>();
            String s = sc.next();
            char ss[] = s.toCharArray();
            nums.push(Integer.parseInt(s.substring(0, 1)));
            for(int j = 1; j <= 3; j++){
            	
                char c = ss[j*2-1];
                int x = Integer.parseInt(s.substring(j*2, j*2+1));
                if(c=='x'){
                    x=nums.pop()*x;
                }else if(c=='/'){
                    x=nums.pop()/x;
                }else{
                    operators.push(c);
                }
                nums.push(x);
            }
            int result=nums.get(0);
            for(int j = 1; j < nums.size(); j++) {
                if(operators.get(j-1) == '+')
                    result += nums.get(j);
                else
                	result -= nums.get(j);
            }

            if(result==24)
                System.out.println("Yes");
            else
                System.out.println("No");
 
        }
 
 
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
06-08

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值