Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Binary numbers of N digits
Next article icon

Binary numbers of N digits

Last Updated : 13 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a positive integer number N. The task is to generate all the binary numbers of N digits. These binary numbers should be in ascending order.

Examples:

Input: 2
Output:
00
01
10
11
Explanation: These 4 are the only binary numbers having 2 digits.

Input: 3
Output:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

 

Approach: For any digit length N, there will be 2N binary numbers. 

  • Therefore traverse from 0 to 2N and convert every number to binary.
  • Store each number and print it at the end.

Below is the implementation of the above approach.

C++
// C++ code to implement above approach #include <bits/stdc++.h> using namespace std;  // Function to convert number // to binary of N bits vector<int> convertToBinary(int num,                              int length) {     // Vector to store the number     vector<int> bits(length, 0);     if (num == 0) {         return bits;     }      int i = length - 1;     while (num != 0) {         bits[i--] = (num % 2);          // Integer division         // gives quotient         num = num / 2;     }     return bits; }  // Function to generate all // N bit binary numbers vector<vector<int> > getAllBinary(int n) {     vector<vector<int> > binary_nos;      // Loop to generate the binary numbers     for (int i = 0; i < pow(2, n); i++) {         vector<int> bits =              convertToBinary(i, n);         binary_nos.push_back(bits);     }      return binary_nos; }  // Driver code int main() {     int N = 3;     vector<vector<int> > binary_nos =          getAllBinary(N);     for (int i = 0; i < binary_nos.size();             i++) {         for (int j = 0;                  j < binary_nos[i].size(); j++)             cout << binary_nos[i][j];         cout << endl;     }     return 0; } 
Java
// Java code for the above approach import java.io.*;  class GFG {    // Function to convert number   // to binary of N bits   static int[] convertToBinary(int num,                                 int length)   {      // Vector to store the number     int[] bits = new int[length];     if (num == 0) {       return bits;     }      int i = length - 1;     while (num != 0) {       bits[i--] = (num % 2);        // Integer division       // gives quotient       num = num / 2;     }     return bits;   }    // Function to generate all   // N bit binary numbers   static int[][] getAllBinary(int n)   {     int[][] binary_nos = new int[(int)Math.pow(2,n)][];     int k = 0;          // Loop to generate the binary numbers     for (int i = 0; i < Math.pow(2, n); i++) {       int[] bits = convertToBinary(i, n);       binary_nos[k++]= bits;     }      return binary_nos;   }    // Driver code   public static void main (String[] args)   {     int N = 3;     int[][] binary_nos = getAllBinary(N);     for (int i = 0; i < binary_nos.length; i++) {       for (int j = 0; j < binary_nos[i].length; j++)         System.out.print(binary_nos[i][j]);       System.out.println();     }    } };  // This code is contributed by Potta Lokesh 
Python3
# Python 3 code to implement above approach  # Function to convert number # to binary of N bits def convertToBinary(num,                     length):      # Vector to store the number     bits = [0]*(length)     if (num == 0):         return bits      i = length - 1     while (num != 0):         bits[i] = (num % 2)         i -= 1          # Integer division         # gives quotient         num = num // 2      return bits  # Function to generate all # N bit binary numbers def getAllBinary(n):      binary_nos = []      # Loop to generate the binary numbers     for i in range(pow(2, n)):         bits = convertToBinary(i, n)         binary_nos.append(bits)      return binary_nos  # Driver code if __name__ == "__main__":      N = 3     binary_nos = getAllBinary(N)     for i in range(len(binary_nos)):         for j in range(len(binary_nos[i])):             print(binary_nos[i][j], end="")         print()          # This code is contributed by ukasp. 
C#
// C# code for the above approach using System; using System.Collections.Generic; public class GFG  {    // Function to convert number   // to binary of N bits   static List<int> convertToBinary(int num, int length) {      // List to store the number     List<int> bits = new List<int>();     if (num == 0) {       bits.Add(0);       bits.Add(0);       bits.Add(0);       return bits;     }      int i = length - 1;     while (num != 0) {       bits.Add(num % 2);        // int division       // gives quotient       num = num / 2;     }     while(bits.Count<3)       bits.Add(0);     return bits;   }    // Function to generate all   // N bit binary numbers   static List<List<int>> getAllBinary(int n) {     List<List<int>> binary_nos = new List<List<int>>();      // Loop to generate the binary numbers     for (int i = 0; i < Math.Pow(2, n); i++) {       List<int> bits = convertToBinary(i, n);       binary_nos.Add(bits);     }      return binary_nos;   }    // Driver code   public static void Main(String[] args) {     int N = 3;     List<List<int>> binary_nos = getAllBinary(N);     foreach(var st in binary_nos){       foreach(var s in st){         Console.Write(s);       }       Console.WriteLine();     }   } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>     // JavaScript code to implement above approach      // Function to convert number     // to binary of N bits     const convertToBinary = (num, length) => {         // Vector to store the number         let bits = new Array(length).fill(0);         if (num == 0) {             return bits;         }          let i = length - 1;         while (num != 0) {             bits[i--] = (num % 2);              // Integer division             // gives quotient             num = parseInt(num / 2);         }         return bits;     }      // Function to generate all     // N bit binary numbers     const getAllBinary = (n) => {         let binary_nos = [];          // Loop to generate the binary numbers         for (let i = 0; i < parseInt(Math.pow(2, n)); i++) {             let bits = convertToBinary(i, n);             binary_nos.push(bits);         }          return binary_nos;     }      // Driver code      let N = 3;     let binary_nos = getAllBinary(N);     for (let i = 0; i < binary_nos.length;         i++) {         for (let j = 0;             j < binary_nos[i].length; j++)             document.write(binary_nos[i][j]);         document.write("<br/>");     }      // This code is contributed by rakeshsahni  </script> 

 
 


Output
000 001 010 011 100 101 110 111


 

Time Complexity: O(2N)
Auxiliary Space: O(2N)


 


Next Article
Binary numbers of N digits

C

code_r
Improve
Article Tags :
  • Bit Magic
  • Mathematical
  • DSA
  • number-digits
  • binary-representation
Practice Tags :
  • Bit Magic
  • Mathematical

Similar Reads

    Count of Binary Digit numbers smaller than N
    Given a limit N, we need to find out the count of binary digit numbers which are smaller than N. Binary digit numbers are those numbers that contain only 0 and 1 as their digits, like 1, 10, 101, etc are binary digit numbers. Examples: Input : N = 200 Output : 7 Count of binary digit number smaller
    6 min read
    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 = 2Output: 1, 10Explanation: The first two non-zero numbers with digits as 0 and 1 onlyInput: n = 5Output: 1, 10, 11, 100, 101[Simple Approach] Using Bit ManipulationWe
    5 min read
    Count unset bits of a number
    Given a number n, count unset bits after MSB (Most Significant Bit).Examples : Input : 17 Output : 3 Binary of 17 is 10001 so unset bit is 3 Input : 7 Output : 0 A Simple Solution is to traverse through all bits and count unset bits. C++ // C++ program to count unset bits in an integer #include <
    7 min read
    Binary representation of a given number
    Given an integer n, the task is to print the binary representation of the number. Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length.Examples: Input: n = 2Output: 00000000000000000000000000000010Input: n = 0Output: 000000000000
    6 min read
    Count of N-bit binary numbers without leading zeros
    Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.Examples: Input: N = 2 Output: 2 10 and 11 are the only possible binary numbers.Input: N = 4 Output: 8 Approach: Since the numbers cannot have leading zeros so the left-most bit has to be set to 1. Now fo
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences