Generate Binary Representations from 1 to n (original) (raw)
Last Updated : 20 Sep, 2025
Given an integer **n, Generate the binary representations of all numbers from 1 to n.
**Examples:
**Input: n = 4
**Output: [1, 10, 11, 100]
**Explanation:
Binary representation of 1 → 1
Binary representation of 2 → 10
Binary representation of 3 → 11
Binary representation of 4 → 100**Input: n = 6
**Output: [1, 10, 11, 100, 101, 110]
**Explanation:
Binary representation of 1 → 1
Binary representation of 2 → 10
Binary representation of 3 → 11
Binary representation of 4 → 100
Binary representation of 5 → 101
Binary representation of 6 → 110
Table of Content
- [Naive Approach] Using Bit Manipulation - O(n log(n)) Time and O(1) Space
- [Expected Approach] Using Queue - O(n) Time and O(n) Space
[Naive Approach] UsingBit Manipulation - O(n log(n)) Time and O(1) Space
The idea is to traverse for all numbers from 1 to n and generate their binary representations.
C++ `
#include #include #include
using namespace std;
vector generateBinary(int n) { vector result;
for (int num = 1; num <= n; num++) {
int temp = num;
string binary = "";
// Convert decimal number to binary
while (temp > 0) {
int rem = temp % 2;
if (rem == 0)
binary += "0";
else
binary += "1";
temp = temp / 2;
}
// reverse to get correct order
reverse(binary.begin(), binary.end());
result.push_back(binary);
}
return result;}
int main() { int n = 6; vector binaries = generateBinary(n);
for (auto bin : binaries)
cout << bin << " ";
cout << endl;
return 0;}
Java
import java.util.ArrayList; import java.util.Collections;
class GfG { static ArrayList generateBinary(int n) { ArrayList result = new ArrayList();
for (int num = 1; num <= n; num++) {
int temp = num;
String binary = "";
// Convert decimal number to binary
while (temp > 0) {
int rem = temp % 2;
if (rem == 0)
binary += "0";
else
binary += "1";
temp = temp / 2;
}
// reverse to get correct order
StringBuilder sb = new StringBuilder(binary);
binary = sb.reverse().toString();
result.add(binary);
}
return result;
}
public static void main(String[] args) {
int n = 6;
ArrayList<String> binaries = generateBinary(n);
for (String bin : binaries)
System.out.print(bin + " ");
System.out.println();
}}
Python
def generateBinary(n): result = []
for num in range(1, n + 1):
temp = num
binary = ""
# Convert decimal number to binary
while temp > 0:
rem = temp % 2
if rem == 0:
binary += '0'
else:
binary += '1'
temp = temp // 2
# reverse to get correct order
binary = binary[::-1]
result.append(binary)
return resultif name == 'main': n = 6 binaries = generateBinary(n)
for bin in binaries:
print(bin, end=' ')
print()C#
using System; using System.Collections.Generic; using System.Linq;
class GfG { static List generateBinary(int n) { List result = new List();
for (int num = 1; num <= n; num++) {
int temp = num;
string binary = "";
// Convert decimal number to binary
while (temp > 0)
{
int rem = temp % 2;
if (rem == 0)
binary += "0";
else
binary += "1";
temp = temp / 2;
}
// reverse to get correct order
char[] binaryArray = binary.ToCharArray();
Array.Reverse(binaryArray);
binary = new string(binaryArray);
result.Add(binary);
}
return result;
}
public static void Main() {
int n = 6;
List<string> binaries = generateBinary(n);
foreach (var bin in binaries)
Console.Write(bin + " ");
Console.WriteLine();
}}
JavaScript
function generateBinary(n) { let result = [];
for (let num = 1; num <= n; num++) {
let temp = num;
let binary = "";
// Convert decimal number to binary
while (temp > 0) {
let rem = temp % 2;
if (rem === 0)
binary += '0';
else
binary += '1';
temp = Math.floor(temp / 2);
}
// reverse to get correct order
binary = binary.split('').reverse().join('');
result.push(binary);
}
return result;}
// Driver Code let n = 6; let binaries = generateBinary(n);
console.log(binaries.join(' '));
`
Output
1 10 11 100 101 110
[Expected Approach] Using Queue - O(n) Time and O(n) Space
We use a queue to perform level-order traversal of a conceptual binary tree where the root is "1", the left child is formed by appending "0", and the right child by appending "1". In each step, dequeue a number, store it, and enqueue its "0" and "1" extensions until n binary numbers are generated.
**Why this Works:
- BFS ensures we generate numbers **level by level, which corresponds exactly to **decimal order: "1", "10", "11", "100", "101", "110", ..."
- Each node’s left child is always smaller than its right child in binary, preserving correct ordering.
- Since we only generate n numbers, we get all binary numbers from 1 to n **in order.
**Note: In JavaScript, there is no built-in queue data structure, so we create a custom queue class.
C++ `
#include #include using namespace std;
vector generateBinary(int n){
vector res;
queue q;
// Enqueue the first binary number
q.push("1");
// This loops is like BFS of a tree with "1" as root
// "0" as left child and "1" as right child and so on
while (n--) {
string s1 = q.front();
q.pop();
res.push_back(s1);
string s2 = s1;
if(q.size() < n) {
// Append "0" to s2 and enqueue it.
q.push(s1.append("0"));
// Append "1" to s2 and enqueue it.
q.push(s2.append("1"));
}
}
return res;}
int main(){ int n = 6;
vector<string> res = generateBinary(n);
for(auto i:res){
cout<<i<<" ";
}
cout<<"\n";
return 0;}
Java
import java.util.Queue; import java.util.LinkedList; import java.util.ArrayList;
class GFG { static ArrayList generateBinary(int n) { ArrayList res = new ArrayList<>(); Queue q = new LinkedList<>();
// Enqueue the first binary number
q.add("1");
// This loop is like BFS of a tree with 1 as root
// 0 as left child and 1 as right child and so on
while (n-- > 0) {
String s1 = q.poll();
res.add(s1);
String s2 = s1;
if(q.size() < n){
// Append "0" to s1 and enqueue it.
q.add(s1 + "0");
// Append "1" to s2 and enqueue it.
q.add(s2 + "1");
}
}
return res;
}
public static void main(String[] args) {
int n = 6;
ArrayList<String> res = generateBinary(n);
for (String i : res) {
System.out.print(i + " ");
}
System.out.println();
}}
Python
from collections import deque
def generateBinary(n): res = [] q = deque()
# Enqueue the first binary number
q.append("1")
# This loop is like BFS of a tree with 1 as root
# 0 as left child and 1 as right child and so on
while n > 0:
# print the front of queue
s1 = q.popleft()
res.append(s1)
s2 = s1
if len(q) < n:
# Append "0" to s1 and enqueue it.
q.append(s1 + "0")
# Append "1" to s2 and enqueue it.
q.append(s2 + "1")
n -= 1
return resif name == "main": n = 6 res = generateBinary(n) for i in res: print(i, end=" ") print()
C#
using System; using System.Collections.Generic;
class GFG { static List generateBinary(int n){ List res = new List(); Queue q = new Queue();
// Enqueue the first binary number
q.Enqueue("1");
// This loop is like BFS of a tree with 1 as root
// 0 as left child and 1 as right child and so on
while (n-- > 0){
string s1 = q.Dequeue();
res.Add(s1);
string s2 = s1;
if (q.Count < n) {
// Append "0" to s1 and enqueue it.
q.Enqueue(s1 + "0");
// Append "1" to s2 and enqueue it.
q.Enqueue(s2 + "1");
}
}
return res;
}
static void Main(){
int n = 6;
List<string> res = generateBinary(n);
foreach (string i in res){
Console.Write(i + " ");
}
Console.WriteLine();
}}
JavaScript
// Custom Queue class class Queue { constructor() { this.size = 0; this.items = {}; this.frontIndex = 0; this.backIndex = 0; }
// Enqueue element at the back
enqueue(item) {
this.items[this.backIndex] = item;
this.backIndex++;
this.size++;
}
// Dequeue element from the front
dequeue() {
if (this.isEmpty()) return null;
const item = this.items[this.frontIndex];
delete this.items[this.frontIndex];
this.frontIndex++;
this.size--;
return item;
}
// Check if queue is empty
isEmpty() {
return this.backIndex === this.frontIndex;
}
getSize() {
return this.size;
}}
// Function to generate first n binary numbers function generateBinary(n) { let res = []; let q = new Queue();
// Enqueue the first binary number
q.enqueue("1");
// This loop is like BFS of a tree with 1 as root
// 0 as left child and 1 as right child and so on
while (n-- > 0) {
let s1 = q.dequeue();
res.push(s1);
let s2 = s1;
if(q.getSize() < n) {
// Append "0" to s1 and enqueue it.
q.enqueue(s1 + "0");
// Append "1" to s2 and enqueue it.
q.enqueue(s2 + "1");
}
}
return res;}
// Driver Code let n = 6; let res = generateBinary(n); console.log(res.join(" "));
`
Output
1 10 11 100 101 110