Given a positive integer n. The problem is to print the numbers in the range 1 to n having bits in alternate pattern. Here alternate pattern means that the set and unset bits in the number occur in alternate order. For example- 5 has an alternate pattern i.e. 101.
Input : n = 10 Output : 1 2 5 10 Input : n = 50 Output : 1 2 5 10 21 42
Method 1 (Naive Approach): Generate all the numbers in the range 1 to n and for each generated number check whether it has bits in alternate pattern. Time Complexity is of O(n).
Method 2 (Efficient Approach): Algorithm:
printNumHavingAltBitPatrn(n) Initialize curr_num = 1 print curr_num while (1) curr_num <<= 1 if n < curr_num then break print curr_num curr_num = ((curr_num) << 1) ^ 1 if n < curr_num then break print curr_num
1 2 5 10 21 42
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.
- Check whether bits are in alternate pattern in the given range | Set-2
- Check whether bits are in alternate pattern in the given range
- Check if a number has bits in alternate pattern | Set 1
- Check if a number has bits in alternate pattern | Set-2 O(1) Approach
- Alternate bits of two numbers to create a new number
- Print numbers having first and last bits as the only set bits
- Count total set bits in all numbers from range L to R
- Check if bits in range L to R of two numbers are complement of each other or not
- Print first n numbers with exactly two set bits
- Copy set bits in a range
- Count set bits in a range
- Check whether all the bits are set in the given range
- Toggle bits in the given range
- Unset bits in the given range
- Set bits in N equals to M in the given range.
- Set all the bits in given range of a number
- Count unset bits in a range
- Range query for count of set bits
- Check whether all the bits are unset in the given range or not
- Python | Count set bits in a range
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Mithun Kumar