An Interesting Method to Generate Binary Numbers from 1 to n?

Here we will see one interesting method for generating binary numbers from 1 to n. This approach uses a queue data structure to generate binary representations in sequence. Initially the queue holds the first binary number '1'. We repeatedly remove elements from the queue, print them, then append '0' and '1' to create the next binary numbers and insert them back into the queue.

Algorithm

genBinaryNumbers(n)
Begin
   define empty queue
   insert "1" into the queue
   while n is not 0, do
      delete element from queue and store it into s1
      print s1
      insert s1 + "0" into queue
      insert s1 + "1" into queue
      decrease n by 1
   done
End

How It Works

The algorithm works by leveraging the binary tree structure −

  • Start with "1" in the queue
  • For each dequeued element, generate two new binary numbers by appending '0' and '1'
  • This creates a breadth−first traversal of the binary number tree
  • Continue until we have generated n binary numbers

Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 1000

typedef struct {
    char data[MAX_SIZE][20];
    int front;
    int rear;
    int count;
} Queue;

void initQueue(Queue* q) {
    q->front = 0;
    q->rear = -1;
    q->count = 0;
}

int isEmpty(Queue* q) {
    return q->count == 0;
}

void enqueue(Queue* q, char* str) {
    q->rear = (q->rear + 1) % MAX_SIZE;
    strcpy(q->data[q->rear], str);
    q->count++;
}

void dequeue(Queue* q, char* result) {
    strcpy(result, q->data[q->front]);
    q->front = (q->front + 1) % MAX_SIZE;
    q->count--;
}

void genBinaryNumbers(int n) {
    Queue q;
    initQueue(&q);
    enqueue(&q, "1");
    
    while (n != 0) {
        char s1[20];
        dequeue(&q, s1);
        printf("%s ", s1);
        
        char temp0[20], temp1[20];
        strcpy(temp0, s1);
        strcpy(temp1, s1);
        strcat(temp0, "0");
        strcat(temp1, "1");
        
        enqueue(&q, temp0);
        enqueue(&q, temp1);
        n--;
    }
}

int main() {
    int n = 15;
    printf("Binary numbers from 1 to %d:
", n); genBinaryNumbers(n); printf("
"); return 0; }
Binary numbers from 1 to 15:
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111

Key Points

  • The algorithm generates binary numbers in lexicographical order
  • Time complexity is O(n) where n is the count of numbers to generate
  • Space complexity is O(n) for the queue storage
  • Each binary number is generated exactly once without conversion from decimal

Conclusion

This queue−based approach elegantly generates binary numbers by building them incrementally. It's more efficient than converting each decimal number to binary and demonstrates the power of BFS traversal in number generation.

Updated on: 2026-03-15T11:13:26+05:30

559 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements