Title Description
Figure out the number of times in 1 of 1~13’s integer, and figure out the number of 1 in 100~1300’s integer. For this reason, he counted the number of 1 in the range of 1 to 13 in particular, 1, 10, 11, 12, 13, so there were six times, but for the latter problem he had no choice. ACMerI hope you can help him, and generalize the problem, you can quickly find out the number of occurrences of 1 in any nonnegative integer interval (from 1 to 1 in n).
thinking
Why suddenly thought of a very indecent way. But it is time-consuming. Traversing the number from 1 to N, turning each number into a string, and see how many times the number of “1” appears.
Answer
class Solution: def NumberOf1Between1AndN_Solution(self, n): # write code here if n<1: return 0 elif n==1: return 1 else: num=0 for i in range(2,n+1): num += str(i).count('1') return num+1