以递增的顺序考虑从1到N(N <= 9)的数字序列:1 2 3 4 ... N在每个数字之间插入'+'(用于加法)或' - '(用于减法)数字使得结果总和为零。打印总和为零的所有可能组合。
答案 0 :(得分:0)
您可以选择两种操作。 N-1次。这给你2 ^(N-1)种可能的组合。只需使用简单整数循环所有这些组合。然后通过查看迭代数的第n位来判断你选择加号还是减号。
int N = ...;
int max = 1 << (N-1); // 2^(N-1)
for (int i = 0; i < max; ++i) // loop over all + and - combinations
{
// start at 1, since you can't put a - in front of the first digit
int sum = 1;
for (int k = 2; k <= N; ++k)
{
if (((i >> (k - 2)) & 1) == 1) // look at bit (k-2)
{
sum += k;
} else
{
sum -= k;
}
}
if (sum == 0)
{
// we found a solution, print binary output:
// 1 means +, 0 means -
// read from right to left!
System.out.println(Integer.toString(i, 2));
}
}
如果输出例如:
100101
然后你有:
+--+-+
从右到左插入数字:
7+6-5-4+3-2+1
答案 1 :(得分:0)
public class AllisNothing
{
private static int digits;
private static String reverse;
private static int k;
private static String rarray[];
public static int getDecimalFromBinary(int binary)
{
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String[] args)
{
int N=7;
int i;
String limit="";
String bin;
digits=N;
int sum;
for(i=0;i<N;i++)
limit=limit+"1";
//System.out.println("limit="+limit);
int temp=Integer.parseInt(limit);
temp=getDecimalFromBinary(temp);
rarray=new String[temp+1];
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
for(int j=0;j<=temp;j++)
{
sum=0;
bin=Integer.toBinaryString(j);
reverse=df.format(Integer.parseInt(bin));
reverse=reverse.replaceAll("1","-");
reverse=reverse.replaceAll("0","+");
char result[]=reverse.toCharArray();
rarray[j]="";
for(k=1;k<=result.length;k++)
rarray[j]=rarray[j]+result[k-1]+""+k+",";
//System.out.println("int="+j+"\treverse="+rarray[j]);
String output[]=rarray[j].split(",");
for(int l=0;l<output.length;l++)
{
if(Integer.parseInt(output[0])<0)
{
sum=-1;
break;
}
sum+=Integer.parseInt(output[l]);
}
if(sum==0)
System.out.println(rarray[j]+"=0");
}
}
}