How to generate all the binary options of N bits in Java

1 Answer

0 votes
public class MyClass
{
	private static void generateAllBinaryOptions(int N) {
		int total_bits = 1 << N; // = 2 ^ N

		for (int i = 0; i < total_bits; i++) {
			String binary = String.format("%4s", Integer.toBinaryString(i)).replaceAll(" ", "0");

			System.out.println(binary);
		}
	}
	public static void main(String[] args)
	{
		int N = 4;

		generateAllBinaryOptions(N);
	}
}





/*
run:
  
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
  
*/

 



answered Aug 25, 2023 by avibootz

Related questions

1 answer 118 views
1 answer 108 views
1 answer 114 views
1 answer 113 views
1 answer 111 views
1 answer 119 views
2 answers 157 views
...