lintcode 3:统计数字

来源:互联网 发布:blct升级数据 编辑:程序博客网 时间:2024/05/21 04:43

题目描述

计算数字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)


直接循环遍历每个数的每一位即可

代码

public static int digitCounts(int k, int n) {        // write your code here        int res = 0;        while(n>=0){            int temp = n;            while (temp>0){                if(temp%10==k){                    res++;                }                temp/=10;            }            n--;        }        if (k==0){            return res+1;        }        return res;    }