【两次过】Lintcode 3:Digit Counts

Count the number of k's between 0 and nk can be 0 - 9.

Example

if n = 12, k = 1 in

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

we have FIVE 1's (1, 10, 11, 12)

解题思路:

    思路很清晰,遍历然后对每个数字分解统计数目即可。

    需要额外注意的是0的特殊情况,具体代码中有。

class Solution {
public:
    /*
     * @param : An integer
     * @param : An integer
     * @return: An integer denote the count of digit k in 1..n
     */
    int digitCounts(int k, int n) 
    {
        // write your code here
        int count = 0;
        
        for(int i=0;i<=n;i++)
            count += contain(k,i);
 
        return count;
    }
    
    //返回数字n分解后存在k的次数
    int contain(int k,int n)
    {
        int count = 0;
        
        //特别注意!由于下面while(n)会忽略掉当n=0的情况,所以需要额外考虑
        if(n == 0 && k == 0)
            count++;
            
        while(n)
        {
            if(k == n%10)
                count++;
            n /= 10;
        }
        
        return count;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80461242