Given a number n, print first n positive integers with exactly two set bits in their binary representation.
Input: n = 3 Output: 3 5 6 The first 3 numbers with two set bits are 3 (0011), 5 (0101) and 6 (0110) Input: n = 5 Output: 3 5 6 9 10 12
A Simple Solution is to consider all positive integers one by one starting from 1. For every number, check if it has exactly two sets bits. If a number has exactly two set bits, print it and increment count of such numbers.
An Efficient Solution is to directly generate such numbers. If we clearly observe the numbers, we can rewrite them as given below pow(2,1)+pow(2,0), pow(2,2)+pow(2,0), pow(2,2)+pow(2,1), pow(2,3)+pow(2,0), pow(2,3)+pow(2,1), pow(2,3)+pow(2,2), ………
All numbers can be generated in increasing order according to higher of two set bits. The idea is to fix higher of two bits one by one. For current higher set bit, consider all lower bits and print the formed numbers.
3 5 6 9
Time Complexity : O(n)
This article is contributed by Bharath Reddy Appareddy. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print numbers having first and last bits as the only set bits
- Print numbers in the range 1 to n having bits in alternate pattern
- Print the number of set bits in each node of a Binary Tree
- Sum of numbers with exactly 2 bits set
- Count total set bits in all numbers from 1 to n
- Count total set bits in all numbers from 1 to n | Set 2
- Alternate bits of two numbers to create a new number
- Check if bits in range L to R of two numbers are complement of each other or not
- Maximum sum by adding numbers with same number of set bits
- Python map function | Count total set bits in all numbers from 1 to n
- Closest (or Next) smaller and greater numbers with same number of set bits
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- First and Last Three Bits
- Same Number Of Set Bits As N