给定一个十进制数N,统计从1开始到N的所有整数中1出现的次数
N=2时,1出现了1次
N=12时,1,10,11,12,则1出现次数为5
肯定不能数每个数字中1的个数,复杂太高。
要分别统计每一位出现的1的次数
而1在每一位出现的次数又有一定的规则:
例如12345,在百位上1出现的次数有:100~199,1100~1199,2100~2199,3100~3199,4100~4199,5100~5199,6100~6199,7100~7199,8100~8199,9100~9199,10100~10199,11100~11199,12100~12199,与低位的数字45无关,(12+1)*100
而对于12045,则在百位上1出现的次数有:
100~199,1100~1199,2100~2199,3100~3199,4100~4199,5100~5199,6100~6199,7100~7199,8100~8199,9100~9199,10100~10199,11100~11199,与低位的数字45无关
12*100
而对于12145,则在百位上1出现的次数有:
100~199,1100~1199,2100~2199,3100~3199,4100~4199,5100~5199,6100~6199,7100~7199,8100~8199,9100~9199,10100~10199,11100~11199,12100~12145,不仅与高位的12有关,与低位的45也有关
12*100+45+1
因此可以推出通用的过程,即从最低位个位到最高位,分别将某一位取出来,并且得到其高位数字和低位数字,统计每一位1出现的次数即可。
def count(n):
factor=1
cnt=0
while n/factor !=0:
higher = int(n/(10*factor))
equal = int((n-higher*10*factor)/factor)
lower = n%factor
if equal==0:
cnt = cnt+higher*factor
elif equal==1:
cnt +=higher*factor+lower+1
else:
cnt += (higher+1)*factor
factor *=10
return cnt