“
对于整数n,我们将这个整数分为三部分:当前位数字cur,更高位数字high,更低位数字low,如:对于n=21034,当位数是十位时,cur=3,high=210,low=4。
我们从个位到最高位 依次计算每个位置出现1的次数:
1)当前位的数字等于0时,例如n=21034,在百位上的数字cur=0,百位上是1的情况有:00100~00199,01100~01199,……,20100~20199。一共有21*100种情况,即high*100;
2)当前位的数字等于1时,例如n=21034,在千位上的数字cur=1,千位上是1的情况有:01000~01999,11000~11999,21000~21034。一共有2*1000+(34+1)种情况,即high*1000+(low+1)。
3)当前位的数字大于1时,例如n=21034,在十位上的数字cur=3,十位上是1的情况有:00010~00019,……,21010~21019。一共有(210+1)*10种情况,即(high+1)*10。
本段引用自https://www.cnblogs.com/yongh/p/9947165.html
”
每个位上的数字都需要结合前一位和后一位才能确定遍历到当前位的时候有多少个当前位为1的情况。
还需要注意的是如何获取当前位的高位数字和低位数字。
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
if(n<=0)
return 0;
int count=0;
for(int i=1;i<=n;i*=10){
int high=n/(i*10);
int low=n%i;
int cur=(n/i)%10;
if(cur==0){
count+=high*i;
}
else if(cur==1){
count+=high*i+low+1;
}
else{
count+=(high+1)*i;
}
}
return count;
}
}