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
- There will be 2n numbers with number of bits from 1 to n.
- Iterate through all 2n numbers. For every number check if it contains consecutive set bits or not. To check, we do bitwise 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 the given number contains consecutive set bits.
Below is the implementation of the above approach:
1 2 4 5
Time Complexity: O(2N)
Auxiliary Space: O(1)
This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes