Java: Generator of true's & false's combinations by giving the number N;

后端 未结 7 2294
野的像风
野的像风 2020-12-09 13:53

I tied to simplify the task as much as possible, so I could apply it to my algorithm.

And here is the challenge for mathematicians and programmers:

I need to

7条回答
  •  误落风尘
    2020-12-09 14:06

    Here is a really basic way using only Java APIs:

    final int n = 3;
    for (int i = 0; i < Math.pow(2, n); i++) {
        String bin = Integer.toBinaryString(i);
        while (bin.length() < n)
            bin = "0" + bin;
        System.out.println(bin);
    }
    

    Result:

    000
    001
    010
    011
    100
    101
    110
    111
    

    Of course, you can set n to whatever you like. And, with this result, you can pick the nth character from the string as true/false.

    If you only need to check if a bit is true, you don't need to convert it to a string. This is just to illustrate the output values.

提交回复
热议问题