这里写自定义目录标题
整数中1出现的次数(从1到n整数中1出现的次数)
描述
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数
例如,1~13中包含1的数字有1、10、11、12、13因此共出现6次
[O(n^2)解法]
class Solution {
public:
int countDigitOne(int n) {
int count = 0;
for (int i = 1; i <= n; ++i)
{
int num = i;
while(num)
{
if (num % 10 == 1)
{
++count;
}
num /= 10;
}
}
return count;
}
};
class Solution {
public:
int countDigitOne(int n) {
int count = 0, high = n / 10, cur = n % 10, low = 0;
long digit = 1;
while (0 != high || 0 != cur)
{
if (0 == cur)
{
count += high * digit;
}
else if (1 == cur)
{
count += high * digit + low + 1;
}
else
{
count += (high + 1) * digit;
}
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return count;
}
};

801

被折叠的 条评论
为什么被折叠?



