class Solution {
public:
int countDigitOne(int n) {
if(n <=0)
return 0;
int ifac = 1;
int front = 0;
int back = 0;
int curr = 0;
int total = 0;
while(ifac <= n)
{
front = n / ifac / 10;
curr = (n - front*ifac*10)/ifac;
back = (n - front*ifac*10)%ifac;
if(curr == 0)
{
total += (front*ifac);
}
else if(curr == 1)
{
total += (front*ifac);
total += (back+1);
}
else
{
total += (front+1)*ifac;
}
if (ifac > INT_MAX / 10)//一定要注意溢出的情况
break;
ifac*=10;
}
return total;
}
};
LeetCode ||Number of Digit One
最新推荐文章于 2022-12-07 22:01:39 发布