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, ten, one, [], we have FIVE 1 ' s (1, ten, one,)
Analysis:
Method 1:directly count every number.
Method 2:analytical solution.
Every time, calculate how many K have appears on a specific postion, i.e., on 1,,.....
Solution 1:
1 classSolution {2 /*3 * param k:as description.4 * param n:as description.5 * Return:an integer denote the count of digit K in 1..N6 */7 Public intDigitcounts (intKintN) {8 int[] record =New int[10];9Arrays.fill (record,0);Ten for(inti=0;i<=n;i++){ OneString temp =integer.tostring (i); A for(intJ=0;j<temp.length (); j + +){ - intIND = (int) (Temp.charat (j)-' 0 '); -record[ind]++; the } - } - returnRecord[k]; - + } -};
Solution 2:
1 classSolution {2 /*3 * param k:as description.4 * param n:as description.5 * Return:an integer denote the count of digit K in 1..N6 */7 Public intDigitcounts (intKintN) {8 intres = 0;9 intBase = 1;Ten while(base<=N) { One intPart1 = n/(base*10); A if(base>1 && k==0 && part1>0) part1--; -Part1 *=Base; - intBar = n/base%10; the intPart2 = 0; - if(k<bar) Part2 =Base; - Else if(k==bar) Part2 = n%base+1; - if(k==0 && n<base*10) part2 = 0; +Res + = part1+Part2; -base*=10; + } A returnRes; at } -};
Lintcode-digit Counts