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 ))
Calculate the numbers in the natural number sequence 1 and 2