对整数逐一进行比较,每一个数字大于0,则先进行取余操作,然后在进行/10,继续循环,看这一个数字里面有多少1。
通过加入对1 和对10 的判断可以提升速度
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
count=0
if n <10:
if n==1 :
return 1
if n==10:
return 2
for n in range(n+1):
while n>0:
if n%10==1:
count+=1
n=n/10
return count如果cur 位为1,high* digit+1+low,如果 cur位为0,high* digit, 如果cur为大于1,(high+1)* digit
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
cur=n%10
high=n//10
low=0
count=0
digit=1
while high!=0 or cur!=0:
if cur==1:
count+=high*digit+1+low
elif cur==0:
count+=high*digit
elif cur>1:
count+=(high+1)*digit
low+=cur*digit
cur=high%10
high=high//10
digit*=10
return count 
京公网安备 11010502036488号