DEV Community

Sadiul Hakim
Sadiul Hakim

Posted on

Algorithm part 5: Generate as many Binary number as you want

Hello, Guys. Today i will show you how you can generate as many Binary numbers as you want.

I'll be using Java Language and Queue Data Structure.

Solution

public String[] generateBinary(int n){
        String[] result=new String[n];
        Queue<String> queue=new LinkedList<>();
        queue.offer("1");


       for(int i=0;i<n;i++){
            String poll=queue.poll();
            String n1=poll+"0";
            String n2=poll+"1";
            result[i]=poll;

            queue.offer(n1);
            queue.offer(n2);

        }
        return result;
    }
Enter fullscreen mode Exit fullscreen mode

Hope this helps you. Thank you ❤.

Top comments (0)