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基础教程

  • 相关阅读:
    maya绝招(1-20)
    maya 操作自我整理(二)
    maya 操作自我整理(一)
    让IE6 IE7 IE8 IE9 IE10 IE11支持Bootstrap的解决方法
    SAP MM Consignment 寄售库存
    java或者jsp中修复会话标识未更新漏洞
    强大!基于拖放布局的 Twitter Bootstrap 网站生成器
    mysql 2003 10038 连接不上的解决
    STRUTS2 标签 循环次数
    tomcat 启用Gzip 压缩进行优化
  • 原文地址:https://www.cnblogs.com/amiza/p/10334295.html
Copyright © 2011-2022 走看看