You don’t need to print anything. It has already been taken care of. Just implement the given function.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case has a single integer ‘N’ for which we need to find the integers containing only 0 and 1
For each test case, print the required count.
1 <= T <= 10^4
1 <= N <= 10^9
Time Limit: 1sec
For every integer between 1 to N , check whether it consists of 1s and 0s only.
If at any moment of time we found that there are other digit apart from 0s and 1s, then we will not count that integer in our answer.
Algorithm:
In this approach, instead of visiting each and every number, we try to use the property of 1s and 0s. We have a range from 1 to N, and we know that 1 is a valid (one digit) number, and the next valid (2 digit) numbers are 10 , 11. So in order to reach 10, 11 from 1, we can simply multiply 1 by 10, and then
Using same thing,
1
/ \
10 11
/ \ / \
100 101 110 111
. . . .
. . . .
If at any point we have reached a number larger than N, we can return from there. This way we are exploring all those numbers that consist of only 1s and 0s.
Since a tree-like structure is forming up, it's easier to use recursion. We only need to work at the root node, and recursion will handle children.
Create a helper function having our number N, and initial node i.e 1.
From 1, make two calls :
After that, add 1 in your ans because of the root node.
So it will look like,
Return helper(N,node*10) + helper(N,node*10+1) + 1
Stopping criteria (Base case)
Whenever we encounter a value greater than N, return 0 as it doesn’t fall in the given range.
Pair Product Div by K
Pair Product Div by K
Merge Two Sorted Arrays Without Extra Space
Merge Two Sorted Arrays Without Extra Space
Co-Prime
First Digit One
Special Digit Numbers