Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/52/
Topics
Count the number K (0<=k<=9) between 0 and N. In the case of n=12, there is a total of 5 1 between [0,1,2...,12]. Included in [1, 10, 11, 12] respectively.
Online test
http://lintcode.com/problem/digit-counts/
Answer
The solution to the problem lies in the skillful use of recursive thinking and preprocessing.
Preprocessing: F[0] represents the number of numbers k in 0-9. (definitely =1) f[1] represents the number of numbers k in 00-99. F[2] represents the number of numbers k in 000-999....
Existing formula: F[i] = f[i-1] * 9 + 10I
G[1] Represents the number of numbers k in 10-99.
G[2] Represents the number of 100-999 numbers K. Existence formula: G[i] = f[i]-f[i-1]//if k! = 0 = f[i]-f[i-1]-10I//If k ==0
Make [A, b] represent how many numbers k is between the-a. Suppose n=2345.[0, 2345] = [0, 999] + [, 1999] + [2345]
here [0, 999] = [0,9] + [ten, +] + [999] = 1 + g[1] + g[2][1999] = [999] = f[2]//k ! = 1[999] + +-f[2] + +//k = = 1
[2000,2345] = [345]//k!=2 = [345] + 346//k==2
[000,345] =[099] + [199] +[299] +[345]= F[1] + 3 * (k==0) + f[1] + (k = = 1) + f[1] + (k = = 2) + [00,45] + * (k = =)
According to the above analysis, we can use the time O (1) to reduce the number of bits of the computed n by one: from the calculation [0, 2345] to the calculation [000,345] to the calculation [00,45].
So the time complexity of the whole algorithm is O (log10 (n))
Nine chapters algorithm surface question 52 numbers