就像生活中常见的密码锁,就是那种几个滚轮的密码锁,固定其中的一位密码,拨动其他位置的密码。
class Solution {
public int countDigitOne(int n) {
int digit=1,cur=n%10,low=0,high=n/10;
int res=0;
while(high!=0||cur!=0){
if(cur==0)res+=high*digit;
else if(cur==1)res+=high*digit+low+1;
else res+=(high+1)*digit;
low+=cur*digit;
digit*=10;
cur=high%10;
high/=10;
}
return res;
}
}
方法二:
class Solution {
public int countDigitOne(int n) {
int k=0,tmp=1;
int ans=0;
while(n>=tmp){
ans+=(n/(tmp*10)*tmp)+Math.min(Math.max(n%(tmp*10)-tmp+1,0),tmp);//(n/(tmp*10)*tmp)整的,例如1163,每1000个数百位上的1出现了100次,计算了1000,那么接着计算163中百位上的1出现了多少次,63次,所以百位总共出现了163次
tmp*=10;
}
return ans;
}
}