python resolves occurrences of 1 in integers from 1 to n

Source: Internet
Author: User

Recently in the "Jian Point offer", face question 32 of the topic: Enter an integer n, the number from 1 to n decimal representation of the n integer 1 occurrences. For example, input 12, from 1 to 12 of these integers contain 1 of the numbers are 1, 10, 11, and 12, 11 have occurred 5 times.

For the book said does not consider the time efficiency of the solution is very good understanding, can be directly completed, but for the other method introduced in the book, did not understand, so according to their own ideas for analysis.

1 digits, 1-9, 11 appeared 1 times;

2 digits, 10-99, 10-19 of the ten on a total of 10*1=10 times, for each 10 digits of the beginning of the number 10-19, 20-29, each number of digits on the occurrence of 1-9 in 1 occurrences of the number of 9 intervals 9*1=9 times;

3 digits, 100-999,100-199 Hundred appeared 10**2=100 times, for each hundred number beginning, for example 100-199, 200-299, Low is actually 0-99 this interval 1 occurrences, altogether 9 intervals 9*19=171 times;

It is inferred that for 1-9,10-99,100-999, the number of 1 in each n-digit number formula is:

F (1) = 1

F (2) = 9 * F (1) + 10 * * 1

F (3) = 9 * F (2) + 10 * * 2

F (N) = 9 * F (n-1) + * * (n-1)

From the above analysis, we can determine for any given number, for example, 23456 of this 5-digit number, 10000 of the number contained in the numbers are determined, f (1) +f (2) +f (3) +f (4), this is a recursive process, which can be found in 1-4 bits contains 1 of the total, The functions are as follows:

1 defget_1_digits (n):2     """3 get the total number of 1 between each bit4 :p Aram N: Number of digits5     """6     ifN <=0:7         return08     ifn = = 1:9         return1TenCurrent = 9 * Get_1_digits (n-1) + * * (n-1) One     returnGet_1_digits (n-1) + current

From The above analysis, we know how many of the 23456, 1-10000 have appeared in the total number of 1. The next step is to analyze the 1 contained in 10000-23456.

We first take the highest position alone to analyze, to find out the number of top 1, if the highest bit is 1, then the top of the total will appear on the number of 1 is low on the +1, for example 12345, the highest level of a total of 2,346 1; If the highest bit is greater than 1, The total number of occurrences is 10000-19999 altogether 10**4.

Then, depending on the highest bit, the number of 1 in all the numbers in the same number of digits in front of the high position is calculated. For example, 34567, you need to calculate the number of 10000-19999,20000-29999 secondary, this time to calculate the number, that is, calculate the number of 1 in 0-9999, which can be converted to the above F (n) to calculate, call the above function can be directly obtained, It is then multiplied by the resulting value and the difference between the highest and 1 (where the highest level is 3).

After analyzing the above section, we now only have the highest bit behind, we find that the remainder is still an integer, for example, 23456 left 3456, this time directly using the recursive processing of the remaining 3456 on the line. The specific code is as follows:

1 defget_1_nums (n):2     ifN < 10:3         return1ifN >= 1Else04digit = Get_digits (n)#Number of digits5Low_nums = Get_1_digits (digit-1)#The number of 1 before the highest bit6high = int (str (n) [0])#Highest bit7Low = N-high * * * (DIGIT-1)#Low8 9     ifHigh = = 1:TenHigh_nums = low + 1#The number of top 1 OneAll_nums =high_nums A     Else: -High_nums = ten * * (digit-1) -All_nums = high_nums + low_nums * (high-1)#if the highest bit is greater than 1, count the 1 that is included after each multi-digit number the     returnLow_nums + all_nums + get_1_nums (Low)

for the Get_digits function used above, it is used to find a given n is a number of digits. The code is as follows:

1 def get_digits (n): 2     # to find the number of bits of an integer n 3     ret = 04while       N:5         ret + 16         n/= 10 7     return RET

in order to compare the efficiency of the operation, I use each iteration of the number of 1 of the method to compare the number of times, found that using the above method of efficiency improved a lot, given the number of larger, the more obvious efficiency improvement. The general solution is as follows:

1 deftest_n (num):2     #conventional methods are used to compare3RET =04      forNinchRange (1, num+1):5          forSinchstr (n):6             ifs = ='1':7RET + = 18     returnRet

The following code was used to test and found that the efficiency improvements were obvious:

1 if __name__=='__main__':2Test = 99234463     Import Time4t =Time.clock ()5     Printtest_n (test)6     PrintTime.clock ()-T7T1 =Time.clock ()8     Printget_1_nums (test)9     PrintTime.clock ()-T1

the results of the operation are as follows, and the operating rate has been increased many times:

697009518.28474569700950.000223999999999

for the implementation of this problem source code, please get here.

python resolves occurrences of 1 in integers from 1 to n

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.