问题:
给定一个自然数N,计算1,2,3...N中,出现1和2的数量。比如1,2,3...10,一共出现了3次,1,2,3...12,一共出现了7次。
思路:
比如计算54321,可以先计算50000,再计算50001-54321中1和2的个数,而后者又可以看成计算4321中1和2的个数,于是简化了问题。其中计算50000的时候,可以计算49999中有多少个1和2,也就递归转变成了一个已知的求解方法,再加上50000所代表的1和2的个数(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 // 这个方法计算1000、50000这种以0结尾的数字中1和2的个数 def count_head(number): number_str = str(number) 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))
原文地址:http://blog.csdn.net/oswin/article/details/40383979