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

这是一道来自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技术文章欢迎访问我的博客:www.yuanrenxue.com

转载于:https://my.oschina.net/JUANererer/blog/3025801

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值