360笔试题-修复方程
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int i = 0; i < T; i++) { String equa = sc.next(); boolean res = canMakeEquationTrue(equa); if (res) { System.out.println("Yes"); } else { System.out.println("No"); } } sc.close(); } private static boolean canMakeEquationTrue(String equa) { String[] parts = equa.split("="); String leftPart = parts[0]; String rightPart = parts[1]; long leftV = getValue(leftPart); long rightV = getValue(rightPart); if (leftV == rightV) { return true; } else if (leftV < rightV) { if (changeExpression(leftPart, rightV)) { // 只调整值更小的表达式 return true; } else { return false; } } else { if (changeExpression(rightPart, leftV)) { return true; } else { return false; } } } // 判断是否能通过添加一位数,使得表达式值变为target private static boolean changeExpression(String expression, long target) { int l = 0, r = 0; // 记录一个数的左右边界 for (int i = 0; i <= expression.length(); i++) { char ch = i < expression.length() ? expression.charAt(i) : ' '; if (ch >= '0' && ch <= '9') { // 数字 r++; } else { // 操作符 for (int j = l; j <= r; j++) { for (int digit = 0; digit <= 9; digit++) { if (j == 0 && digit == 0) continue; String newExpr = expression.substring(0, l) + expression.substring(l, j) + (char) ('0' + digit) + expression.substring(j, r) + expression.substring(r); if (getValue(newExpr) == target) { return true; } } } r++; l = r; } } return false; } // 计算表达式的值 private static long getValue(String expression) { String[] adds = expression.split("\\+"); long result = 0L; for (String addStr : adds) { String[] muls = addStr.split("\\*"); long temp = 1L; for (String mulStr : muls) { temp *= mulStr == "" ? 1L : Long.valueOf(mulStr); } result += temp; } return result; } }
考试的时候没完全ac,这是后面自己整理的一版java解法,供各位家人们参考~也可以帮我验证检查看是否存在什么问题,欢迎大家评论指导。
#360笔试题##25秋招#