zoukankan      html  css  js  c++  java
  • LintCode-Digit Counts

    Count the number of k's between 0 and n. k can be 0 - 9.

    Example

    if n=12, in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], we have FIVE 1's (1, 10, 11, 12)

    Analysis:

    Method 1: directly count every number.

    Method 2: Analytical solution.

    Every time, calculate how many k has appears on a specific postion, i.e., on 1, 10, 100,.....

    Solution 1:

     1 class Solution {
     2     /*
     3      * param k : As description.
     4      * param n : As description.
     5      * return: An integer denote the count of digit k in 1..n
     6      */
     7     public int digitCounts(int k, int n) {
     8         int[] record = new int[10];
     9         Arrays.fill(record,0);
    10         for (int i=0;i<=n;i++){
    11             String temp = Integer.toString(i);
    12             for (int j=0;j<temp.length();j++){
    13                 int ind = (int) (temp.charAt(j)-'0');
    14                 record[ind]++;
    15             }
    16         }
    17         return record[k];
    18                 
    19     }
    20 };

    Solution 2:

     1 class Solution {
     2     /*
     3      * param k : As description.
     4      * param n : As description.
     5      * return: An integer denote the count of digit k in 1..n
     6      */
     7     public int digitCounts(int k, int n) {
     8         int res = 0;
     9         int base = 1;
    10         while (base<=n){
    11             int part1 = n/(base*10);
    12             if (base>1 && k==0 && part1>0) part1--;
    13             part1 *= base;
    14             int bar = n/base%10;
    15             int part2 = 0;
    16             if (k<bar) part2 = base;
    17             else if (k==bar) part2 = n%base+1;
    18             if (k==0 && n<base*10) part2 = 0;
    19             res += part1+part2;
    20             base*=10;
    21         }
    22         return res;    
    23     }
    24 };
  • 相关阅读:
    高性能Javascript 选择器API学习笔记
    Backbone学习笔记二 Events
    递归用函数、存储过程实现的效果
    用触发器实现动态新增列
    局域网自动备份删除
    游标变量用法经典
    如何区分大小写字母、全角半角
    列的分拆显示
    2005的行列转换
    批量分离和附加数据库
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4194962.html
Copyright © 2011-2022 走看看