Calculate the numbers in the natural number sequence 1 and 2
Problem:
Given a natural number N, calculate the numbers of 1 and 2 in 1, 2, 3... N. For example, 1, 2, 3... 10, appear 3 times, 1, 2, 3... 12, appear 7 times in total.
Ideas:
For example, to calculate 54321, you can calculate 50000 first, and then calculate the numbers of 1 and 2 in 4321-54321. The latter can be regarded as the number of 1 and 2 in, which simplifies the problem. When we calculate 50000, we can calculate the number of 1 and 2 in 49999, and recursively convert it into a known solution, add the number of 1 and 2 represented by 50000 (0 ).
Def count_from_number (number): if number <10: if number = 0: return 0 elif number = 1: return 1 else: return 2 number_str = str (number) first = number_str [0] left = number_str [1:] head = first + len (left) * '0' count = 0 count + = count_head (int (head )) if first = '1' or first = '2': count + = (number-int (head) count + = count_from_number (int (left )) return count // This method calculates the numbers def count_head (number): number_str = str (number) in numbers 1 and 2 ending with 0, 1000) first = number_str [0] count = 0 if first = '1' or first = '2': count + = 1 count + = count_from_number (number-1) return count number = 10 print ("count 1 or 2 for % d" % number) print ("result: % d" % count_from_number (number )) number = 12 print ("count 1 or 2 for % d" % number) print ("result: % d" % count_from_number (number )) number = 122 print ("count 1 or 2 for % d" % number) print ("result: % d" % count_from_number (number ))