Ninja has an integer ‘N’. Ninja is fond of digit ‘1’ so Ninja wants to know the number of 1s in each number from 0 to N.
Your task is to help the Ninja in finding out the number of ones from 0 to ‘N’.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first and only line of the test case consists of a single integer ‘N’.
Output Format
Return the total number of one digit.
1 <= ‘T’ <= 11
1 <= ‘N’ <= 10^9
Time Limit: 1 sec
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
2
10
14
2
7
For the first test case:-
The number of 1’s in 1 is 1
The number of 1’s in 2 is 0
The number of 1’s in 3 is 0
The number of 1’s in 4 is 0
The number of 1’s in 5 is 0
The number of 1’s in 6 is 0
The number of 1’s in 7 is 0
The number of 1’s in 8 is 0
The number of 1’s in 9 is 0
The number of 1’s in 10 is 1
For the first test case hence answer is 2.
For the second test case:-
The number of 1’s in 1 is 1
The number of 1’s in 2 is 0
The number of 1’s in 3 is 0
The number of 1’s in 4 is 0
The number of 1’s in 5 is 0
The number of 1’s in 6 is 0
The number of 1’s in 7 is 0
The number of 1’s in 8 is 0
The number of 1’s in 9 is 0
The number of 1’s in 10 is 1
The number of 1’s in 11 is 2
The number of 1’s in 12 is 1
The number of 1’s in 13 is 1
The number of 1’s in 14 is 1
For the first test case hence answer is 7.
2
9
15
1
8
Count the number of ones from 0 to N.
The main idea is to run a loop from 0 to N and count the number of ones for every integer from 0 to N.
Algorithm :
O(N * log10(N)) where ‘N’ is the given number.
For every integer from 0 to N, we are traversing its digits which takes O(log10(N)). Hence total time complexity is O(N * log10(N)).
O(1)
We are using constant space to solve this.