码迷,mamicode.com
首页 > 编程语言 > 详细

LintCode上的一道算法面试题: 数字的统计

时间:2019-01-29 18:19:03      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:code   while   统计   for   应该   end   解决   The   www.   

说到数字的统计,小时候的数学课大家都应该有学过,但数字太多太复杂的,手动肯定耗时间不说还很容易出错。所以今天分享一下如何用程序来完成。

Have you met this question in a real interview? 你是否在真实的采访中遇到过这个问题?

Count the number of k‘s between 0 and nk can be 0 - 9.计算0到n之间的k的数量。 k可以是0-9。

这道来自LintCode的算法题目,主要是教大家如何从以下数字中统计某一个数字出现的次数。下面我将用C++来帮大家解答这道题:

Description题目描述

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

计算0到n之间的k的数量。 k可以是0-9。

Example样例

例如n=12,k=1

在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],we have FIVE 1‘s (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;
    }
};

  

原题目链接地址: https://www.lintcode.com/problem/digit-counts/description

如果你有其它更好的算法来解决这个问题,欢迎留言讨论。文章来自于猿人学笔记:www.yuanrenxue.com

LintCode上的一道算法面试题: 数字的统计

标签:code   while   统计   for   应该   end   解决   The   www.   

原文地址:https://www.cnblogs.com/amiza/p/10334295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!