What I am trying to do is print all the possibilities of a binary number n digits long. In other words, with a 4 digit number:
0001
0010
0100
1000
..etc
To be honest, I have no idea of where to even start with this (other than I figure I'd need to use a loop, and probably an array) so any pointers in the right direction would be appreciated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With