您现在的位置是:首页 > 文章详情

【LintCode: 3. 统计数字】算法题解析

日期:2019-03-11点击:362

这是一道来自LintCode的算法题目,本文用C++来解答这道题,链接为: https://www.lintcode.com/problem/digit-counts/description

题目描述

计算数字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=1时,对于整数1111,一共出现了4次,也就是判断每一位上的数字是不是1, 数字1111共有4位,就要对其判断4次,从个位开始,除以10取余数即可。

按照这个思路,代码如下:

代码

#include #include <sys/time.h> class Solution { public: /** * @param k: An integer * @param n: 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++) { int t = i; while(t > 9) { int gewei = t % 10; if(gewei == k) count ++; t = t / 10; } if (t == k) count++; } return count; } }; 

如果你有其它更好的算法来解决这个问题,欢迎留言讨论。

文章来自于猿人学博客:Python教程

原文链接:https://yq.aliyun.com/articles/693335
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章