您的位置:首页 > 其它

LeetCode OJ 之 Number of Digit One (数字1的个数)

2017-05-25 21:20 134 查看

题目:

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:

Given n = 13,

Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

思路:

对这个数字的每一位求存在1的数字的个数。

从个位開始到最高位。

举个样例54215。比方如今求百位上的1,54215的百位上是2。能够看到xx100到xx199的百位上都是1,这里xx从0到54。即100->199, 1100->1199...54100->54199, 这些数的百位都是1,因此百位上的1总数是55*100

假设n是54125,这时因为它的百位是1,先看xx100到xx199。当中xx是0到53,即54*100, 然后看54100到54125,这是26个。所以百位上的1的总数是54*100 + 26.

假设n是54025。那么仅仅须要看xx100到xx199中百位上的1,这里xx从0到53,总数为54*100

求其它位的1的个数的方法是一样的。

代码:

class Solution {
public:
int countDigitOne(int n)
{
int res=0;
long left, right, base=1;
if (n <= 0)
return 0;
while (n >= base)
{
left = n / base;   //left包括当前位
right = n % base;  //right为当前位的右半边

if ((left % 10) > 1)
res+= (left / 10 + 1) * base;

else if ((left % 10) == 1)
res+= (left / 10) * base+ (right + 1);

else
res+= (left / 10) * base;
base *= 10;
}
return res;
}

};
能够把上面三个条件合成一步。例如以下:

class Solution {
public:
int countDigitOne(int n)
{
int res=0;
long left, right, base=1;
if (n<=0)
return 0;
while (n>=base)
{
left = n / base;   //left包括当前位
right = n % base;  //right为当前位的右半边

res += ((left + 8) / 10 * base) + (left % 10 == 1) * (right + 1);
base *= 10;
}
return res;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: