20min,一次性通过,想法比较巧妙,按照阶梯来进行计数,难点在于边界条件的确定,有点麻烦。
import math
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
digit=math.floor(math.log(n,10))+1 if n!=0 else 1
cnt=0
for i in range(1,digit+1): # 最后i要到digit+1
rest=min(10**(i-1),max(0,n%(10**i)-10**(i-1)+1))
cnt+=n//(10**i)*(10**(i-1))+rest
return cnt
参考如下代码,由于没有使用位数,显得较为简略不容易出错
链接:https://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6?f=discussion
来源:牛客网
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
if(n <= 0)
return 0;
int count = 0;
for(long i = 1; i <= n; i *= 10){
long diviver = i * 10;
count += (n / diviver) * i + Math.min(Math.max(n % diviver - i + 1, 0), i);
}
return count;
}
}
网友评论