9.9 360 修复方程

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < n; i++) {
            String s = br.readLine();
            res.append(invoke(s)?"Yes":"No").append("\n");
        }
        System.out.println(res);
    }

    static boolean invoke(String s){
        if(handler(s)) return true;
        boolean flag=false;
        //第一层循环找插入字符位置
        for (int i = 0; i <=s.length() ; i++) {
            //第二层循环插入0-9
            for (int j = 0; j < 10; j++) {
                flag|=handler(s.substring(0,i)+j+s.substring(i));
            }
        }
        return flag;
    }
    //把等式拆开,比较两边相等
    static boolean handler(String s) {
        int i = s.indexOf('=');
        return execute(s.substring(0,i))==execute(s.substring(i+1));
    }
    //计算单一的式子(模拟计算器,只有乘加,所以比较简单)
    static int execute(String s) {
        char[] chars = s.toCharArray();
        int tem = chars[0] - '0';
        Stack<Integer> numstack = new Stack<>();
        Stack<Character> charstack = new Stack<>();
        for (int i = 1; i < s.length(); i++) {
            char c = chars[i];
            if (Character.isDigit(c)) {
                tem = tem * 10 + c - '0';
            } else {
                numstack.push(tem);
                tem = 0;
                if (c == '+') {
                    while (!charstack.empty() && charstack.peek() == '*') {
                        charstack.pop();
                        numstack.push(numstack.pop() * numstack.pop());
                    }
                }
                charstack.push(c);
            }
        }
        numstack.push(tem);
        while (!charstack.empty()) {
            Character pop = charstack.pop();
            if(pop=='+'){
                numstack.push(numstack.pop() + numstack.pop());
            }else {
                numstack.push(numstack.pop() * numstack.pop());
            }
        }
        return numstack.pop();
    }
}

#360笔试#
全部评论
楼主厉害啊
点赞
送花
回复
分享
发布于 2022-09-25 19:34 陕西

相关推荐

7 2 评论
分享
牛客网
牛客企业服务