VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-all-binary-numbers-in-range-l-r-with-same-length/

⇱ Generate all binary numbers in range [L, R] with same length - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate all binary numbers in range [L, R] with same length

Last Updated : 23 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. The length of all binary numbers should be same.

Examples:

Input: L = 2, R = 4
Output:
010
011
100
Explanation: The binary representation of the numbers: 2 = 10, 3 = 11 and 4 = 100.
For the numbers to have same length one preceding 0 is added to the binary representation of both 3 and 4.

Input: L = 2, R = 8
Output:
0010
0011
0100
0101
0110
0111
1000

Approach: Follow the approach mentioned below to solve the problem.

  • To determine the length of resultant binary numbers, take log of R+1 to the base 2.
  • Then traverse from L to R and convert every number to binary of determined length.
  • Store each number and print it at the end.

Below is the implementation of the above approach

 
 


Output
0010
0011
0100
0101
0110
0111
1000


 

Time Complexity: O(N * logR) where N = (R - L + 1)
Auxiliary Space: O(N * logR)


 

Comment