Print list of binary permutations

Maybe you could use a recursive algorithm:

public void printBin(String soFar, int iterations) {
    if(iterations == 0) {
        System.out.println(soFar);
    }
    else {
        printBin(soFar + "0", iterations - 1);
        printBin(soFar + "1", iterations - 1);
    }
}

You would execute this like this:

printBin("", 4);

That would give you all possible binary numbers with 4 digits.

Hope this helped!


For an n-bit binary number, there are 2^n "permutations". You just need to loop over the integers from 0 to (1<<n)-1, and convert each one to binary.


for(int i=0; i < 128; i++){
  System.out.println(Integer.toBinaryString(i));
}

Adjust the max for as high as you'd like to go.

If you need the padded 0's, there was another question on that just today: Pad a binary String equal to zero ("0") with leading zeros in Java

Tags:

Algorithm

Java