LintCode(3)-统计数字

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

思路:通过c++中的count函数来查找

#include <string>

class Solution {

public:

    int digitCounts(int k, int n) {

        // write your code here

        int c = 0;

        for(int i = 0; i <= n; i++)

        {

            string s = to_string(i);//将int型转换成string

            c = c + count(s.begin(), s.end(), k+'0');

        }

        return c;

    }

};

时间复杂度应该是o(n),应该不是最优解。

猜你喜欢

转载自blog.csdn.net/Qmingwt/article/details/125822430