zoukankan      html  css  js  c++  java
  • 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基础教程

  • 相关阅读:
    ES6中关于数据类型的拓展:Symbol类型
    ES里关于数组的拓展
    ES里关于对象的拓展
    ES6里关于函数的拓展(三)
    ES6里关于函数的拓展(二)
    ES6里关于函数的拓展(一)
    ES6里关于正则表达式的拓展
    ES6里关于模板字面量的拓展
    Android之怎样实现滑动页面切换【Fragment】
    java quartz的使用,做时间轮询调用 CronTrigger
  • 原文地址:https://www.cnblogs.com/amiza/p/10334295.html
Copyright © 2011-2022 走看看