Given a positive integer n, print all n-bit binary numbers having more 1’s than 0’s for any prefix of the number.
Input : n = 2 Output : 11 10 Input : n = 4 Output : 1111 1110 1101 1100 1011 1010
A simple but not efficient solution will be to generate all N-bit binary numbers and print those numbers that satisfy the conditions. The time complexity of this solution is exponential.
An efficient solution is to generate only those N-bit numbers that satisfy the given conditions. We use recursion. At each point in the recursion, we append 0 and 1 to the partially formed number and recur with one less digit.
1111 1110 1101 1100 1011 1010
This article is contributed by Pranav. 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.
- Print all distinct integers that can be formed by K numbers from a given array of N numbers
- Prefixes with more a than b
- Shift all prefixes by given lengths
- Check whether two strings can be made equal by increasing prefixes
- Python | Count all prefixes in given string with greatest frequency
- Print all the Paths of a Binary Tree whose XOR is non-zero
- Print Binary Search Tree in Min Max Fashion
- Print all Coprime path of a Binary Tree
- Print Palindromic Paths of Binary tree
- Print Bottom-Right View of a Binary Tree
- Print all Palindromic Levels Of a Binary Tree
- Print all Prime Levels of a Binary Tree
- Print the nodes of Binary Tree having a grandchild
- Print path between any two nodes in a Binary Tree | Set 2
- Given two binary strings perform operation until B > 0 and print the result
- Program to print modified Binary triangle pattern
- Print all leaf nodes of a Binary Tree from left to right
- How will you print numbers from 1 to 100 without using loop? | Set-2
- How will you print numbers from 1 to 100 without using loop?
- Print the longest path from root to leaf in a Binary tree