Q: 数字1-9依次排列:1,2,3,4,5,6,7,8,9;在每两个数之间填“+”或“-”,或不填,如:12+3-4+5+6+7+8+9。使它的值恰好等于100.
有多少种填法?
例如:123-4-5-6-7+8-9=100
程序如下:
public class Test1 {
private int num;
public Test1(int num) {
super();
this.num = num;
}
public void getString() {
int[] arr = new int[8];
for(int i1=0;i1<3;i1++) {
arr[0]=i1;
for(int i2=0;i2<3;i2++) {
arr[1]=i2;
for(int i3=0;i3<3;i3++) {
arr[2]=i3;
for(int i4=0;i4<3;i4++) {
arr[3]=i4;
for(int i5=0;i5<3;i5++) {
arr[4]=i5;
for(int i6=0;i6<3;i6++) {
arr[5]=i6;
for(int i7=0;i7<3;i7++) {
arr[6]=i7;
for(int i8=0;i8<3;i8++) {
arr[7]=i8;
String str = "1";
for(int i=0;i<arr.length;i++) {
if(arr[i]==0) {
str = str+(i+2);
}
if(arr[i]==1) {
str = str+"+"+(i+2);
}
if(arr[i]==2) {
str = str+"-"+(i+2);
}
}
int a =getValue(str);
if(num==a) {
System.out.println(str+"="+a);
}
}
}
}
}
}
}
}
}
}
public int getValue(String str) {
StringBuffer sb = new StringBuffer(str);
int index1 = sb.indexOf("+");
int index2 = sb.indexOf("-");
ArrayList<Integer> arrList = new ArrayList<Integer>();
int sign = 0;
while(index1>0||index2>0) {
String str0;
if((index1<index2&&index1>0)||index2<0) {
if(sign==0) {
str0 = sb.substring(0, index1);
}else {
str0 = "-"+sb.substring(0, index1);
}
sb.delete(0, index1+1);
sign = 0;
}else {
if(sign==0) {
str0 = sb.substring(0, index2);
}else {
str0 = "-"+sb.substring(0, index2);
}
sb.delete(0, index2+1);
sign = 1;
}
int num = new Integer(str0);
arrList.add(num);
index1 = sb.indexOf("+");
index2 = sb.indexOf("-");
}
if(sign==0) {
arrList.add(new Integer(sb.toString()));
}else {
arrList.add(new Integer("-"+sb.toString()));
}
int sum = 0;
for(int i=0;i<arrList.size();i++) {
sum = sum+arrList.get(i);
}
return sum;
}
public static void main(String[] args) {
Test1 t1 = new Test1(100);
t1.getString();
}
}
结果:
123+45-67+8-9=100
123+4-5+67-89=100
123-45-67+89=100
123-4-5-6-7+8-9=100
12+3+4+5-6-7+89=100
12+3-4+5+67+8+9=100
12-3-4+5-6+7+89=100
1+23-4+56+7+8+9=100
1+23-4+5+6+78-9=100
1+2+34-5+67-8+9=100
1+2+3-4+5+6+78+9=100