CSP认证201903-2-二十四点-(Java)100分

二十四点

问题描述
试题编号: 201903-2
试题名称: 二十四点
时间限制: 1.0s
内存限制: 512.0MB
在这里插入图片描述
Java满分代码
在这里插入图片描述
Java代码

import  java.util.Scanner;

public class Main {
    public static int cul(int num1, Character type, int num2){
        switch (type){
            case 'x':
                return num1*num2;
            case '/':
                return num1/num2;
            case '+':
                return num1+num2;
            default:
                return num1-num2;
        }
    }

    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] output = new String[n];
        for(int i = 0;i < n;i++){
            String str = sc.next();
            int[] num = {Integer.valueOf(str.charAt(0))-48, Integer.valueOf(str.charAt(2))-48,
                    Integer.valueOf(str.charAt(4))-48, Integer.valueOf(str.charAt(6))-48};

            int[] oper = {0, 0, 0};     // 运算符优先级 0代表+或-, 1代表x或/
            int index = 0;
            for(int j = 1;j <= 5;j += 2, index++)
                if(str.charAt(j) == 'x' || str.charAt(j) == '/')
                    oper[index] = 1;
            int oper_res = 0;
            if(oper[0] == 1) oper_res += 4;
            if(oper[1] == 1) oper_res += 2;
            if(oper[2] == 1) oper_res += 1;

            int res = 0;
            switch (oper_res){
                case 1:     // 两边运算符优先 0 0 1
                case 5:     //             1 0 1
                    res = cul(cul(num[0], str.charAt(1), num[1]), str.charAt(3), cul(num[2], str.charAt(5), num[3]));
                    break;
                case 2:     // 中间运算符优先 0 1 0
                case 3:     // 后边运算符优先 0 1 1
                    int mid = cul(num[1], str.charAt(3), num[2]);
                    int right = cul(mid, str.charAt(5), num[3]);
                    res = cul(num[0], str.charAt(1), right);
                    break;
                default:    // 按顺序 0 0 0 , 1 0 0 , 1 1 0 , 1 1 1
                    res = cul(num[0], str.charAt(1), num[1]);
                    res = cul(res, str.charAt(3), num[2]);
                    res = cul(res, str.charAt(5), num[3]);
            }

            output[i] = (res == 24) ? "Yes" : "No";
        }
        for(int i = 0;i < n;i++)
            System.out.println(output[i]);
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值