The Wayback Machine - https://web.archive.org/web/20211220053106/https://www.geeksforgeeks.org/convert-all-numbers-in-range-l-r-to-binary-number/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Convert all numbers in range [L, R] to binary number

  • Last Updated : 19 Dec, 2021

Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. 

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: L = 1, R = 4
Output: 
1
10
11
100
Explanation: The binary representation of the numbers 1, 2, 3 and 4 are: 
1 = (1)2
2 = (10)2
3 = (11)2
4 = (100)2



Input: L = 2, R = 8
Output:
10
11
100
101
110
111
1000

 

Approach: The problem can be solved using following approach.

  • Traverse from L to R and convert every number to binary number.
  • Store each number and print it at the end.

Below is the implementation of the above approach.

C++




// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to convert a number 
// to its binary equivalent
vector<int> convertToBinary(int num)
{
    vector<int> bits;
    if (num == 0) {
        bits.push_back(0);
        return bits;
    }
  
    while (num != 0) {
        bits.push_back(num % 2);
  
        // Integer division
        // gives quotient
        num = num / 2;
    }
    reverse(bits.begin(), bits.end());
    return bits;
}
  
// Function to convert all numbers 
// in range [L, R] to binary
vector<vector<int> > getAllBinary(int l, 
                                  int r)
{
    // Vector to store the binary 
    // representations of the numbers
    vector<vector<int> > binary_nos;
    for (int i = l; i <= r; i++) {
        vector<int> bits = 
            convertToBinary(i);
        binary_nos.push_back(bits);
    }
    return binary_nos;
}
  
// Driver code
int main()
{
    int L = 2, R = 8;
    vector<vector<int> > binary_nos = 
        getAllBinary(L, R);
    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;
}
Output
10
11
100
101
110
111
1000

Time Complexity: O(N * LogR) Where N is the count of numbers in range [L, R]
Auxiliary Space: O(N * logR)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!