360 笔试 修复方程 AC代码
import java.util.Scanner;
/**
* @author metaxylene 2022-9-9 17:25
*/
public class Main15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] strs = new String[n];
for (int i = 0; i < strs.length; i++) {
String[] leftAndRight = in.next().split("=");
// 等式左边
String left = leftAndRight[0];
// 等式右边
String right = leftAndRight[1];
// 等式左边原始结果
long leftRes = stringResult(left);
// 等式右边原始结果
long rightRes = stringResult(right);
// 左边原始结果等于右边原始结果
if (leftRes == rightRes) {
System.out.println("Yes");
} else {
// 比较左右两边修改之后的结果
// 此处需要优化为比较两边的原始结果大小再修改表达式,我这里纯粹着急了没想到
// 等式左边进行修改
if (equals(left, rightRes)) {
System.out.println("Yes");
// 等式右边进行修改
} else if (equals(right, leftRes)) {
System.out.println("Yes");
// 都不对
} else {
System.out.println("No");
}
}
}
}
/**
* 计算表达式结果
*/
public static long stringResult(String left) {
// 加号分割乘法表达式
String[] LPlus = left.split("\\+");
long sum = 0;
for (int i = 0; i < LPlus.length; i++) {
long res = 1;
String[] temp = LPlus[i].split("\\*");
// 计算乘法
for (int j = 0; j < temp.length; j++) {
res *= Long.parseLong(temp[j]);
}
// 计算加法
sum += res;
}
return sum;
}
/**
* 修改字符串数位,对有数字的地方后面加0-9(暴力)
* 传入的s是表达式,another是另一边的计算结果
*/
public static boolean equals(String s, long another) {
StringBuilder sb = new StringBuilder();
sb.append(s);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 如果这一位是数字
if (c >= '0' && c <= '9') {
for (int j = 0; j < 10; j++) {
// 在这个数字后加0-9依次进行
sb.insert(i + 1, j + "");
// 加上数字之后计算结果如果和另一边相符 返回
if (stringResult(sb.toString()) == another) {
return true;
}
// 删除添加的数字
sb.delete(i + 1, i + 2);
}
}
}
return false;
}
} #360公司##笔试#

SHEIN希音公司福利 370人发布