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
- 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
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