CCF 201903-2 二十四点-java
100分
import java.util.*;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int n;
n=s.nextInt();
for(int i=0;i<n;i++) {
String a;
a=s.next();
char[] ch=new char[3];//存三个字符
ch[0]=a.charAt(1);
ch[1]=a.charAt(3);
ch[2]=a.charAt(5);
int[] num=new int[4];//存四个数字
num[0]=a.charAt(0)-'0';
num[1]=a.charAt(2)-'0';
num[2]=a.charAt(4)-'0';
num[3]=a.charAt(6)-'0';
for(int j=0;j<3;j++) {
String c=new String(ch);//每次重新生成字符串 每次会变化 乘除时将发生运算符号后的运算符前移,最后一个字符改变为‘a'
int f=c.indexOf('x');//寻找第一个x所在位置
// System.out.println(f);
int d=c.indexOf('/');
if(f!=-1||d!=-1) {//----x或/ 确定乘除顺序
int t=0;
if(f==-1)
t=d;
else if(d==-1)
t=f;
else {
if(f<d)
t=f;
else
t=d;
}
int x=yunsuan(num[t],ch[t],num[t+1]); //运算
//System.out.println(t+" "+num[t]+" "+ch[t]+" "+num[t+1]);
num[t]=x;
for(int k=t+1;k<3-j;k++)//前移云算数
num[k]=num[k+1];
for(int l=t;l<2-j;l++)//前移运算符
{
ch[l]=ch[l+1];
}
ch[2-j]='a';
}
else {//+ -从前往后运算
int x=yunsuan(num[0],ch[0],num[1]);
//System.out.println("+/-"+j+" "+num[2-j]+" "+ch[2-j]+" "+num[3-j]);
num[0]=x;
for(int k=1;k<3-j;k++)
num[k]=num[k+1];
for(int l=0;l<2-j;l++)
{
ch[l]=ch[l+1];
}
}
}
if(num[0]==24)
System.out.println("Yes");
else
System.out.println("No");
}
}
public int first(char ch[]) {
int x=-1;
for(int i=0;i<ch.length;i++) {
if(ch[i]=='x'||ch[i]=='/')
x=i;
}
return x;
}
public static int yunsuan(int x,char c,int y) {//运算一步
int z=0;
if(c=='+')
z=x+y;
if(c=='-')
z=x-y;
if(c=='x')
z=x*y;
if(c=='/')
z=x/y;
return z;
}
}