...

/

Solution Review: Generate Binary Numbers From 1 to N Using Queue

Solution Review: Generate Binary Numbers From 1 to N Using Queue

This review provides a detailed analysis to help you solve the "Generate Binary Numbers From 1 to N Using Queue" challenge.

We'll cover the following...

Solution: Using a queue #

Press + to interact
main.cs
DoublyLinkedList.cs
Queue.cs
using System;
using System.Collections;
namespace chapter_4
{
class Challenge_1
{
//Start with Enqueuing 1.
//Dequeue a number from queue and append 0 to it and enqueue it back to queue.
//Perform step 2 but with appending 1 to the original number and enqueue back to queue.
//Queue takes integer values so before enqueueing it make sure to convert string to integer.
//Size of Queue should be 1 more than number because for a single number we're enqueuing two
//variations of it , one with appended 0 while other with 1 being appended.
static string [] findBin(int n)
{
string [] result = new string[n];
Queue queue = new Queue();
queue.Enqueue(1);
string s1, s2;
for (int i = 0; i < n; i++)
{
result[i] = queue.Dequeue().ToString();
s1 = result[i] + "0";
s2 = result[i] + "1";
queue.Enqueue(Convert.ToInt32(s1));
queue.Enqueue(Convert.ToInt32(s2));
}
return result;
}
static void Main(string[] args)
{
var output = findBin(4);
for (int i = 0; i < 4; i++)
Console.Write(output[i] + " ");
return;
}
}
}

The crux of the solution is to generate consecutive binary numbers from previous binary numbers by appending 0 and 1 to each of them. For example:

  • 10 and 11 can be generated when 0 and 1 are appended to 1.
  • 100
...