23,408
社区成员




public class Test {
public static final String OPERATORS = " +-*";
public static final int STEP_LIMIT = 12;
public static final BigDecimal VALUE = BigDecimal.valueOf(2);
public static void main(String[] args) throws Exception {
int[] operators = new int[STEP_LIMIT];
Scanner scanner = new Scanner(System.in);
System.out.println("Please input A:");
String aStr = scanner.next();
BigDecimal a = new BigDecimal(aStr);
System.out.println("Please input B:");
String bStr = scanner.next();
BigDecimal b = new BigDecimal(bStr);
if (find(a, b, operators, 0)) {
System.out.println(toExpression(a, b, operators));
} else {
System.out.println("Oops!");
}
}
public static boolean find(BigDecimal from,
BigDecimal to,
int[] operators,
int step) throws Exception {
if (step >= STEP_LIMIT) {
return false;
}
if (from.compareTo(to) == 0) {
return true;
}
for (int operator = 1; operator < OPERATORS.length(); operator++) {
operators[step] = operator;
if (find(newValue(from, operator), to, operators, step + 1)) {
return true;
}
}
operators[step] = 0;
return false;
}
public static BigDecimal newValue(BigDecimal from, int operator) {
switch (operator) {
case 1:
return from.add(VALUE);
case 2:
return from.subtract(VALUE);
case 3:
return from.multiply(VALUE);
default:
throw new RuntimeException();
}
}
public static String toExpression(BigDecimal a, BigDecimal b, int[] operators) {
StringBuilder buff = new StringBuilder(30).append(a);
for (int i = 0; i < operators.length && operators[i] != 0; i++) {
int operator = operators[i];
buff.append(OPERATORS.charAt(operator)).append(VALUE);
}
return buff.append("=").append(b).toString();
}
}