求这个程序的算法！！在线等，急！！！！！！

raingi520 2011-11-02 01:10:28

...全文
92 2 点赞 打赏 收藏 举报

2 条回复

shine333 2011-11-02
``````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);
String aStr = scanner.next();
BigDecimal a = new BigDecimal(aStr);
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:
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();
}
}
``````

• 打赏
• 举报

raingi520 2011-11-02

A如何通过 +2、-2、*2 这三种运算操作，在12次运算（包含12次）以内得出B
• 打赏
• 举报

2.3w+

Java 非技术区

2011-11-02 01:10