欢迎使用CSDN-markdown编辑器

来源:互联网 发布:淘宝联盟优惠卷设置 编辑:程序博客网 时间:2024/06/06 09:10

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

这种类型的编程题,当毫无头绪的时候,适宜用最原始的方法去分析,即对每个数字去遍历,最终获得次数。
当然,在时间复杂度方面是远远不够的,但是在30分钟的笔试时间里,最机智方法莫过于这种
以下附上代码

代码:

class Solution {    /*     * param k : As description.     * param n : As description.     * return: An integer denote the count of digit k in 1..n     */    public int digitCounts(int k, int n) {        // write your code here      int res = 0;        if(k == 0){            res += 1;        }        while(n!=0){            int tmp = n;            while(tmp!=0){                  int digital = tmp % 10;                if(digital == k){                    res += 1;                }                tmp /= 10;            }            n--;        }        return res;    }};

代码参考[http://heimingx.cn/2016/04/02/lintcode3-count-numbers/]

原创粉丝点击