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.
- How to swap two numbers without using a temporary variable?
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Add two numbers without using arithmetic operators
- Swap bits in a given number
- Swap all odd and even bits
- Russian Peasant (Multiply two numbers using bitwise operators)
- Toggle all the bits of a number except k-th bit.
- Subtract two numbers without using arithmetic operators
- Copy set bits in a range