第九题
匪警请拨110,即使手机欠费也可拨通!
为了保障社会秩序,保护人民群众生命财产安全,警察叔叔需要与罪
犯斗智斗勇,因而需要经常性地进行体力训练和智力训练!
某批警察叔叔正在进行智力训练:
1 2 3 4 5 6 7 8 9 = 110;
请看上边的算式,为了使等式成立,需要在数字间填入加号或者减号
(可以不填,但不能填入其它符号)。之间没有填入符号的数字组合成一
个数,例如:12+34+56+7-8+9 就是一种合格的填法;123+4+5+67-89 是
另一个可能的答案。
请你利用计算机的优势,帮助警察叔叔快速找到所有答案。
每个答案占一行。形如:
12+34+56+7-8+9
123+4+5+67-89
......
代码:
public class Num9 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
recallWrite("123456789", 1);
}
public static void recallWrite(String v, int num) {
if (num == 9) {
if (calcuIntFString(v) == 110)
System.out.println(v);
} else {
char c = v.charAt(v.indexOf("" + num));
recallWrite(v.replace(c + "", c + "+"), num + 1);
recallWrite(v.replace(c + "", c + "-"), num + 1);
recallWrite(v, num + 1);
}
}
/*
* 从字符串中计算值,特殊符号要转义
*/
public static int calcuIntFString(String s) {
int v = 0;
String[] tmps = s.split("\\+");
for (String ts : tmps) {
String[] tmps1 = ts.split("\\-");
int tmp = Integer.valueOf(tmps1[0]);
for (int j = 1; j < tmps1.length; j++)
tmp -= Integer.valueOf(tmps1[1]);
v += tmp;
}
return v;
}
}