Nine chapters algorithm surface question 52 numbers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.