Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation.
Input : n = 4 Output : 1 2 4 5 8 9 10 These are numbers with 1 to 4 bits and no consecutive ones in binary representation. Input : n = 3 Output : 1 2 4 5
1) There will be 2n numbers with number of bits from 1 to n.
2) Iterate through all 2n numbers. For every number check if it contains consecutive set bits or not. To check, we do bit wise and of current number i and left shifted i. If the bitwise and contains a non-zero bit (or its value is non-zero), then given number doesn’t contain consecutive set bits.
Complexity O(2^n) because ‘for’ loop is run 2^n time.
1 2 4 5
This article is contributed by Devanshu Agarwal. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- How to swap two numbers without using a temporary variable?
- Count total set bits in all numbers from 1 to n
- Add two numbers without using arithmetic operators
- Binary representation of a given number
- Russian Peasant (Multiply two numbers using bitwise operators)
- Check if binary representation of a number is palindrome
- Subtract two numbers without using arithmetic operators
- 1's and 2's complement of a Binary Number
- Gray to Binary and Binary to Gray conversion
- Count strings with consecutive 1's
- Print first n numbers with exactly two set bits
- Find Two Missing Numbers | Set 2 (XOR based solution)
- Check if a number can be expressed as a sum of consecutive numbers
- Length of the Longest Consecutive 1s in Binary Representation
- Check if bits of a number has count of consecutive set bits in increasing order
- XOR counts of 0s and 1s in binary representation
- Maximum 0's between two immediate 1's in binary representation
- Efficient method for 2's complement of a binary string
- Multiplication of two numbers with shift operator
- Check divisibility in a binary stream