首页 > 代码库 > LintCode-Digit Counts

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 };

 

LintCode-Digit Counts