Given a limit N, we need to find out the count of binary digit numbers which are smaller than N. Binary digit numbers are those numbers that contain only 0 and 1 as their digits, like 1, 10, 101, etc are binary digit numbers.
Input : N = 200
Output : 7
Count of binary digit number smaller than N is 7,
1, 10, 11, 110, 101, 100, 111
One simple way to solve this problem is to loop from 1 to N and check each number whether it is a binary digit number or not. If it is a binary digit number, increase the count of such numbers, but this procedure will take O(N) time. We can do better, as we know that the count of such numbers will be much smaller than N. We can iterate over binary digit numbers only and check whether generated numbers are smaller than N or not. In the code below, the BFS-like approach is implemented to iterate over only binary digit numbers. We start with 1 and each time we will push (t*10) and (t*10 + 1) into the queue where t is the popped element. If t is a binary digit number, then (t*10) and (t*10 + 1) will also number, so we will iterate over these numbers by only using the queue. We will stop pushing elements in the queue when popped number crosses the N.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. 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.
Please Login to comment...