题目描述
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
思路
求1~n整数中1出现的次数(《剑指offer》面试题43) - Excaliburer - 博客园 这篇博客写的很好
当前位为x
- 如果x>1:(高位数字+1)*10^(i-1)
- 如果x==1:高位数字*10^(i-1)+(低位数字+1)
- 如果x<1:高位数字*10^(i-1)
- 高位数字=n / 10^i
- 当前位:temp=n / 10^(i-1) cur=temp%10
- 低位数字=n - temp*10^(i-1)
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
if n<1:
return 0
high=n
i=1
res=0
while high>0:
high=n/10**i
temp=n/10**(i-1)
cur=temp%10
low=n-temp*10**(i-1)
if cur>1:
res+=(high+1)*10**(i-1)
elif cur<1:
res+=high*10**(i-1)
else:
res+=high*10**(i-1)+(low+1)
i+=1
return res
转化成字符求解
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
count = 0
for i in range(1,n+1):
ss = str(i)
for j in range(len(ss)):
if ss[j]=='1':
count+=1
return count
测试用例
if __name__=='__main__':
s=Solution()
n=2019
print(s.NumberOf1Between1AndN_Solution(n))