繁体   English   中英

二进制计数的可能组合

[英]possible combination in binary counting

考虑从 1 到 N (N<=9) 按升序排列的数字序列: 1 2 3 4 ... N 在每个数字之间插入一个“+”(用于加法)或“-”(用于减法),以便结果和为零。 打印总和为零的所有可能组合。

您可以在两种操作之间进行选择。 对于 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
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");


    }


   }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM