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

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

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

 

文章首发于我的技术博客猿人学Python基础教程

posted @ 2019-01-29 15:25  阿米扎  阅读(334)  评论(0编辑  收藏  举报