思路,累加每一位是1的数量
高位,当前位,低位。位因子代表个位(1),十位(10)
当前位分为三种情况
当前位小于1,res+=高位*位因子,
当前为等于1,res+=高位*位因子+低位+1
当前为大于1,res+=(高位+1)*位因子
即:
switch(cur){
case 0:res+=high*digit;break;
case 1:res+=high*digit+low+1;break;
case 2:res+=(high+1)*dight;break;
}
low=low+cur*dight;//依次更新low、cur、high、digit
cur=high%10;
high/=10;
digit*=10;
代码:
class Solution {
public:
int countDigitOne(int n) {
int res=0;
long digit=1;
int cur=n%10,high=n/10,low=0;
while(cur||high){
switch(cur){
case 0:res+=high*digit;break;
case 1:res+=high*digit+low+1;break;
default: res+=(high+1)*digit;break;
}
low=cur*digit+low;
cur=high%10;
high/=10;
digit*=10;
}
return res;
}
};