zoukankan      html  css  js  c++  java
  • lintcode 中等题:digits counts 统计数字

    题目

    计算数字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。

    class Solution {
        /*
         * param k : As description.
         * param n : As description.
         * return: An integer denote the count of digit k in 1..n
         */
        public int digitCounts(int k, int n) {
            // write your code here
             int count = 0;
             for(int i = 0 ;i <= n ; i ++){
                 int m = i;
                 if(m==0&&k==0){
                     count+=1;
                 }else{
                     while(m!=0){
                         if(m%10==k){
                             count++;
                         }
                         m=m/10;
                     }
                 }
                 
                 
             }
             return count;
        }
    };
    Java Code

    总耗时: 2487 ms

    class Solution:
        # @param k & n  two integer
        # @return ans a integer
        def digitCounts(self, k, n):
            count = 0
            for i in range(n+1):
                l = list(str(i))
                count+=l.count(str(k))
            return count 
    Python Code

    总耗时: 404 ms

    Python 直接list后统计k出现的次数,貌似更简单了

  • 相关阅读:
    EduCF-69 Array Splitting (连续子序列,规律)
    Subsequence 单调队列
    HDU
    HDU
    Numpy 切片和索引
    Numpy 从数值范围创建数组
    Numpy 的常用属性 和创建数组
    Numpy 线性代数
    Numpy 矩阵库(Matrix)
    Numpy 创建数组
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4924296.html
Copyright © 2011-2022 走看看