24点游戏,例如4+5+6+7 可以得出该值为22 不是24 故输出No
例1x2x6x2 该值为24 输出Yes 输入样例里的‘x’为称号 其余为运算符+ - /为加减除
4个数字在0-9之间
虽然办法很笨,但适合处理这种题目。这里的0-9数字等于放水了,倘若是10以上的数字或者是负数,这种方法就不适用!
如有问题,后期题目出来,我再运行更正一下,这个答案是考试结束从现场拍回来的代码,不知道手敲是不是有纰漏,但思想就是下面这样,大体不差。不存在技巧,就是正面刚~
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//存储每一次输入的算术字符串
List<String> list= new ArrayList<String>();
//有几个这种字符串
int n = sc.nextInt();
//存储最终的结果"Yes" "No"
String[] result = new String[n];
//开始输入 beging
for(int i = 0;i<n;i++){
//输入的算术字符串
String str = sc.next();
//每一次输入算术字符串都把list清空,上一次输入残留的字符串不要了
list.clear();
//将输入的运算公式放在一个String数组中
for(int j = 0;j<str.length();j++){
list.add(str.substring(j,j+1));
}
//将乘法和除法解决掉,让剩下的字符串只包含加减运算
for(int w = 0;w<list.size()-1;w++){
//如果是乘法运算符"x"
if(list.get(w).equals("x")){
//取出这个符号两边的数字
int num1 = Integer.parseInt(list.get(w-1));
int num2 = Integer.parseInt(list.get(w+1));
//把结果变成字符串放在target变量中
String target = (num1*num2)+"";
//把w+1和w位置的元素移除
list.remove(w+1);
list.remove(w);
list.set(w-1, target);
//从头再找,看有没有"x"
w = 0;
}else if(list.get(w).equals("/")){
//取出这个符号两边的数字
int num1 = Integer.parseInt(list.get(w-1));
int num2 = Integer.parseInt(list.get(w+1));
//把结果变成字符串放在target变量中
String target = (num1/num2)+"";
//把w+1和w位置的元素移除
list.remove(w+1);
list.remove(w);
list.set(w-1, target);
//从头再找,看有没有"/"
w = 0;
}
}
//处理加减运算
for(int y = 0;y<list.size()-1;y++){
if(list.get(y).equals("+")){
//取出这个符号两边的数字
int num1 = Integer.parseInt(list.get(y-1));
int num2 = Integer.parseInt(list.get(y+1));
//把结果变成字符串放在target变量中
String target = (num1+num2)+"";
//把w+1和w位置的元素移除
list.remove(y+1);
list.remove(y);
list.set(y-1, target);
//从头再找,看有没有"+"
y = 0;
}else if(list.get(y).equals("-")){
//取出这个符号两边的数字
int num1 = Integer.parseInt(list.get(y-1));
int num2 = Integer.parseInt(list.get(y+1));
//把结果变成字符串放在target变量中
String target = (num1-num2)+"";
//把w+1和w位置的元素移除
list.remove(y+1);
list.remove(y);
list.set(y-1, target);
//从头再找,看有没有"+"
y = 0;
}
}
//到这里list中就只剩一个元素了
if(Integer.parseInt(list.get(0))==24){
result[i] = "Yes";
}else{
result[i] = "No";
}
}//end
sc.close();
for(int i = 0;i<result.length;i++){
System.out.println(result[i]);
}
}
}