3 统计数字

原题网址:http://www.lintcode.com/zh-cn/problem/digit-counts/#

计算数字k在0到n中的出现的次数,k可能是0~9的一个值

样例

例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)

标签 
 
思路:暴力循环,遍历每个数的每个位进行对比。
若k不属于0~9或者n小于0,返回0;
 
 
int digitCounts(int k, int n)
{
    if (k<0||k>9||n<0)
    {
        return NULL;
    }
    int result=0;
    if (k==0)
    {
        result=1;
    }
    for (int i=0;i<=n;i++)
    {
        int j=i;
        while(j>0)
        {
            if (j%10==k)
            {
                result++;
            }
            j=j/10;
        }
    }
    return result;
}

其他参考:

标记:编程之美中有另一种算法(链接如下),未看。

https://blog.csdn.net/aphysia/article/details/77528304   

 
原文地址:https://www.cnblogs.com/Tang-tangt/p/8835853.html