二十四点java_CCF 201903-2 二十四点 Java版 非最简

package Main;

import java.util.*;

public class Main {

public static void main(String[] args) {

int x = 0;

String str = "";

Scanner sc = new Scanner(System.in);

x = sc.nextInt();

List list = new ArrayList();

for (int i = 0; i < x; i++) {

//使用 next 接收字符串 如果用 nextLine 会直接接收换行 next会对无效字符串进行过滤

str = sc.next();

//每完成一次进行一次list集合清0防止影响下次计算

list.clear();

//读取每个字符以字符串形式放进list集合 因为题目要求是1-9

for (int j = 0; j < str.length(); j++) {

list.add(str.substring(j, j + 1));

}

//先循环进行 乘除运算 知道没有乘除符号为止

for (int s = 0; s < list.size() ; s++) {

if (list.get(s).equals("x")) {

//得到 x 符号前边的数字 和后边的数字 进行运算 结果替换前边数字

int num1 = Integer.parseInt(list.get(s - 1));

int num2 = Integer.parseInt(list.get(s + 1));

list.set(s - 1, String.valueOf(num1 * num2));

//对运算符和后边数字进行清除

//先清除后边的在清楚前边的 或者直接写 2次 remove(s)

list.remove(s + 1);

list.remove(s);

//最后对s的位置归到上一个数字 因为你改动了集合 不然可能会漏掉

s = s-1;

} else if (list.get(s).equals("/")) {

int num1 = Integer.parseInt(list.get(s - 1));

int num2 = Integer.parseInt(list.get(s + 1));

list.set(s - 1, String.valueOf(num1 / num2));

list.remove(s + 1);

list.remove(s);

s = s-1;

}

}

for (int s = 0; s < list.size() ; s++) {

if (list.get(s).equals("+")) {

int num1 = Integer.parseInt(list.get(s - 1));

int num2 = Integer.parseInt(list.get(s + 1));

list.set(s - 1, String.valueOf(num1 + num2));

list.remove(s + 1);

list.remove(s);

s = s-1;

} else if (list.get(s).equals("-")) {

int num1 = Integer.parseInt(list.get(s - 1));

int num2 = Integer.parseInt(list.get(s + 1));

list.set(s - 1, String.valueOf(num1 - num2));

list.remove(s + 1);

list.remove(s);

s = -1;

}

}

//此时list集合只剩下一个数据 判断是不是24即可

//注意 输出流 和输入流不影响 判题机制只判断输出流所以一边输入一边输出不影响

if (Integer.parseInt(list.get(0)) == 24) {

System.out.println("Yes");

} else {

System.out.println("No");

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值