There is such a function f (N). For any positive integer N, it indicates the number of "1" between 0 and N, such as F (1) = 1, F (13) = 6. list all F (n) = N records from 1 to 1234567890, which must be accurate and fast.
I believe that many people can come up with the following solutions immediately:
For (N: N)
{
Determine the number of N containing 1;
Accumulate counters;
}
This is the most direct solution, but unfortunately, the time complexity is O (n * logn ). Because we also need to cyclically judge the number of all operators of the current N, and the time complexity of this judgment is O (logn ).
Next we should think about a more efficient solution. To be honest, this question reminds me of another simple algorithm question:
N is a positive integer that calculates the sum of integers from 1 to n.
Many people use cyclic solutions. Then we can use elementary mathematics knowledge to know S = N * (n + 1)/2, so we can use O (1) time to process it.
Return to this topic and find the ing between result R and N.
The analysis is as follows:
Suppose n is a [n] a [n-1]... A [1], where a [I] (1 <= I <= N) represents the numbers of N.
C [I] indicates the number of numbers from integer 1 to integer a [I]... a [1] that contain number 1.
X [I] indicates the number of numbers from 1 to 10 ^ I-1 that contain Number 1. For example, X [1] indicates the number from 1 to 9. The result is 1; X [2] indicates the number from 1 to 99. The result is 20;
When a [1] = 0, C [1] = 0;
When a [1] = 1, C [1] = 1;
When a [1]> 1, C [1] = 1;
When a [2] = 1, C [2] = A [1] + 1 + C [1] + X [1];
When a [2]> 1, C [2] = A [2] * X [1] + C [1] + 10;
When a [3] = 1, C [3] = A [2] * A [1] + 1 + C [2] + X [2];
When a [3]> 1, C [3] = A [3] * X [2] + C [2] + 10 ^ 2;
......
And so on
When a [I] = 1, C [I] = A [I-1] *... * A [1] + 1 + C [I-1] + X [I-1];
When a [I]> 1, C [I] = A [I] X [I-1] + C [I-1] + 10 ^ (I-1 );
The implementation code is as follows:
Java code {
Function onclick ()
{
DP. Sh. toolbar. copytoclipboard (this); Return false;
}
} "Href =" http://pandonix.javaeye.com/blog/204840 ">
- Public Static IntSearch (Int_ N)
- {
- IntN = _ n/10;
- IntA1 = _ n % 10, A2;
- IntX = 1;
- IntTen = 10;
- IntC = A1 = 0? ;
- While(N> 0)
- {
- A2 = n % 10;
- If(A2 = 0 );
- Else If(A2 = 1) C = A1 + 1 + x + C;
- ElseC = a2 * x + C + ten;
- A1 = 10 * A1 + A2;
- N/= 10;
- X = 10 * x + ten;
- Ten * = 10;
- }
- ReturnC;
- }
public static int search(int _n) { int N = _n/10; int a1 = _n%10,a2; int x = 1; int ten = 10; int c = a1 == 0?0:1; while(N > 0) { a2 = N%10; if(a2 == 0); else if(a2 == 1)c = a1 + 1 + x + c; else c = a2*x + c + ten; a1 = 10*a1 + a2; N /=10; x = 10*x + ten; ten *= 10; } return c; }
The time complexity of the preceding solution is only O (logn)
If you pass by, do you have a better solution? :)