AcWing 3273. 二十四点+JAVA
原题链接
中等
作者:
xiaozuo99
,
2021-03-12 20:03:05
,
所有人可见
,
阅读 568
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 1;i<=n;i++){
String st = sc.next();
if(calc(st) == 24){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
public static int calc(String s){
Stack<Integer> stk = new Stack<>();
char sign = '+'; // 保存上一个数字的符号
int num = 0; // 保存临时数字
int result = 0; //保存最后结果
for(int i = 0;i<s.length();i++){
char cur = s.charAt(i);
if(Character.isDigit(cur)){
num = num*10 +(cur-'0');
}
if(cur=='+' ||cur=='-' ||cur=='/' ||cur=='x' || i == s.length()-1){
switch(sign){
case '+':
stk.push(num);
break;
case '-':
stk.push(-num);
break;
case '/':
stk.push(stk.pop()/num);
break;
case 'x':
stk.push(stk.pop()*num);
break;
}
sign = cur;
num = 0;
}
}
while(!stk.isEmpty()){
result+=stk.pop();
}
return result;
}
}