201903-2 二十四点 Java

思路:
数据结构中,栈可以解决运算的问题。利用压栈和弹栈操作实现(这里用队列模拟)。具体的:
遇到乘除号,弹出栈顶元素,将计算结果压入栈中。遇到加减号,将后面的数一起压入栈中。
注意:
substring方法前闭后开,substring(i, i + 2)取的是i和i+1。
在ASCII码里'0'对应的刚好是48的二进制码,所以用字符串减去'0'即为整数。

import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] s = new String[n];
        sc.nextLine();
        for (int i = 0; i < n; i++) {
            s[i] = sc.nextLine();//存储算式
        }
        int[] stack = new int[4];//定义栈
        for (String str : s) {
            int count = 0;
            int result = 0;
            stack[0] = str.charAt(0) - '0';//将第一个数存入栈中
            for (int i = 1; i < 7; i += 2) {//从第一个运算符号开始扫描所有运算符
                if (str.charAt(i) == 'x') {//遇到乘除号弹出栈顶元素并将结果计算后压入栈顶
                    stack[count] = stack[count] * (str.charAt(i + 1) - '0');
                } else if (str.charAt(i) == '/') {
                    stack[count] = stack[count] / (str.charAt(i + 1) - '0');
                } else {//遇到加减号将数字连同符号一起压入栈顶
                    stack[++count] = Integer.parseInt(str.substring(i, i + 2));
                }
            }
            for (; count >= 0; count--) {//将所有元素弹栈并相加
                result += stack[count];
            }
            if (result == 24)//判断最终结果是否为24
                System.out.println("Yes");
            else
                System.out.println("No");
        }
        sc.close();
    }
}
原文地址:https://www.cnblogs.com/yu-jiawei/p/12376258.html