DEV Community

Cover image for Generate all the binary strings of n bits
Aniket Vaishnav
Aniket Vaishnav

Posted on

Generate all the binary strings of n bits

The point is simple to generate all the binary string of n bits.
Like, n = 3 then
000
001
010
011
100
101
110
111

Overall all 8 binary strings as a result which is simple to determine as the number of possible binary string would be 2n

Why 2?
As we have only 2 character options within a string ie, 0 or 1

Here we set initially zero and till every character is not zero we continue to do so.
Once we reach end and the string is saved, then we go with seting the current character to one and keep doning this.

This process is known as back tracking.

Show me the code

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class BinaryString {
    public static void main(String[] args) {
        int n = (new Scanner(System.in)).nextInt();

        // String here is represented in form of character arry
        // just for sake of simplicity
        char[] s = new char[n]; 

        List<String> resultStrings = new ArrayList<>();

        generateString(s, n, resultStrings);

        System.out.println(resultStrings.stream().collect(Collectors.joining(", ")));
    }

    private static void generateString(char[] s, int n, List<String> resultStrings) {
        if (n == 0) {
            // only one character left
            resultStrings.add(new String(s));
            return;
        }
        s[n - 1] = '0';
        generateString(s, n-1, resultStrings);

        s[n - 1] = '1';
        generateString(s, n-1, resultStrings);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)