Generate all possible strings of n bits.
💻 coding

Generate all possible strings of n bits.

1 min read 108 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to generate all possible strings of n bits using boolean values 0 and 1.
  • 2The solution utilizes recursion to explore all combinations of bits.
  • 3The time complexity of generating these strings is O(2^n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to generate all possible strings of n bits using boolean values 0 and 1."

Generate all possible strings of n bits.

You have been given an integer n that corresponds to the number of bits in an array. the task is to print all the possible strings using those n bits. the array can consist only boolean values (i.e either 0 or 1)

We will be solving this problem using recursion.

public class AllStringsNBits {

	public static void main(String[] args) {
		int n = 5;
		int[] arr = new int[n];
		GenerateAllStringOfNBits(n, arr);
	}

	private static void GenerateAllStringOfNBits(int n,int[] arr) {
		if(n<1) {
			for(int i=0;i<arr.length;i++) {
				System.out.print(arr[i]);
			}
			System.out.println();
		}
		else {
			arr[n-1]=0;
			GenerateAllStringOfNBits(n-1, arr);
			arr[n-1]=1;
			GenerateAllStringOfNBits(n-1, arr);
		}
			
	}

}

The time complexity for the above solution is O(2^n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 16 July 2018 · 1 min read · 108 words

Part of AskGif Blog · coding

You might also like

Generate all possible strings of n bits. | AskGif Blog