Generate Binary Numbers from 1 to n
Given a number n, write a function that generates and prints all binary numbers with decimal values from 1 to n.
Examples:
Input: n = 2
Output: 1, 10
Explanation: The first two non-zero numbers with digits as 0 and 1 onlyInput: n = 5
Output: 1, 10, 11, 100, 101
[Simple Approach] Using Bit Manipulation
We traverse for all numbers from 1 to n and print their binary representations one by one. To get binary representation of a number i, we check the last bit of it by doing bitwise & with 1 and then right shift it to get the next bit.
#include <bits/stdc++.h>
using namespace std;
void genBin(int n) {
for (int i = 1; i <= n; i++) {
string s;
// Get Binary Representation of i
for (int x = i; x; x >>= 1)
s = (x & 1 ? "1" : "0") + s;
cout << s << endl;
}
}
int main() {
genBin(5);
return 0;
}
public class Main {
public static void genBin(int n) {
for (int i = 1; i <= n; i++) {
String s = Integer.toBinaryString(i); // Get Binary Representation of i
System.out.println(s);
}
}
public static void main(String[] args) {
genBin(5);
}
}
def gen_bin(n):
for i in range(1, n + 1):
s = bin(i)[2:] # Get Binary Representation of i
print(s)
if __name__ == '__main__':
gen_bin(5)
using System;
class Program {
static void GenBin(int n) {
for (int i = 1; i <= n; i++) {
string s = Convert.ToString(i, 2); // Get Binary Representation of i
Console.WriteLine(s);
}
}
static void Main() {
GenBin(5);
}
}
function genBin(n) {
for (let i = 1; i <= n; i++) {
let s = i.toString(2); // Get Binary Representation of i
console.log(s);
}
}
genBin(5);
Output
1 10 11 100 101
[Interesting Approach] Using queue
This is an interesting approach as it involves a queue. We consider binary representations as a binary tree (root as 1 and every left child as 0 appended and right as 1 appended to the parent) and do level order traversal of the binary tree. We start by enqueuing the first binary number "1". In each iteration, we dequeue the front number, print it, and generate the next two binary numbers by appending "0" and "1" to the front number. These new numbers are then enqueued, and the process repeats until
n
binary numbers are printed. The queue helps manage the sequence efficiently.
#include <bits/stdc++.h>
using namespace std;
void generatePrintBinary(int n)
{
queue<string> 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--) {
// print the front of queue
string s1 = q.front();
q.pop();
cout << s1 << "\n";
string s2 = s1;
q.push(s1.append("0"));
// Append "1" to s2 and enqueue it.
// Note that s2 contains the previous front
q.push(s2.append("1"));
}
}
int main()
{
int n = 5;
generatePrintBinary(n);
return 0;
}
import java.util.LinkedList;
import java.util.Queue;
public class GfG {
static void generatePrintBinary(int n) {
Queue<String> q = new LinkedList<>();
// Enqueue the first binary number
q.add("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-- > 0) {
// print the front of queue
String s1 = q.poll();
System.out.println(s1);
String s2 = s1;
q.add(s1 + "0");
// Append "1" to s2 and enqueue it.
// Note that s2 contains the previous front
q.add(s2 + "1");
}
}
public static void main(String[] args) {
int n = 5;
generatePrintBinary(n);
}
}
from collections import deque
def generatePrintBinary(n):
q = deque()
# Enqueue the first binary number
q.append("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 > 0:
# print the front of queue
s1 = q.popleft()
print(s1)
s2 = s1
q.append(s1 + "0")
# Append "1" to s2 and enqueue it.
# Note that s2 contains the previous front
q.append(s2 + "1")
n -= 1
if __name__ == "__main__":
n = 5
generatePrintBinary(n)
using System;
using System.Collections.Generic;
class GfG {
static void GeneratePrintBinary(int n) {
Queue<string> q = new Queue<string>();
// Enqueue the first binary number
q.Enqueue("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-- > 0) {
// print the front of queue
string s1 = q.Dequeue();
Console.WriteLine(s1);
string s2 = s1;
q.Enqueue(s1 + "0");
// Append "1" to s2 and enqueue it.
// Note that s2 contains the previous front
q.Enqueue(s2 + "1");
}
}
static void Main() {
int n = 5;
GeneratePrintBinary(n);
}
}
function generatePrintBinary(n) {
let 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-- > 0) {
// print the front of queue
let s1 = q.shift();
console.log(s1);
let s2 = s1;
q.push(s1 + "0");
// Append "1" to s2 and enqueue it.
// Note that s2 contains the previous front
q.push(s2 + "1");
}
}
let n = 5;
generatePrintBinary(n);
Output
1 10 11 100 101