Digit Counts 解题报告

版权声明:转载请注明本文源地址 https://blog.csdn.net/qwe6112071/article/details/72510679

Digit Counts

Description

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

Example

if n = 12, k = 1 in

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

we have FIVE 1’s (1, 10, 11, 12)

实现思路

本题最简单的实现,就是遍历一个1~n,统计每个数字中k出现的个数。
但另一个更简单却也很直接的思路就是:直接统计从1-n中,每一位中可能出现为k的个数。举个例子,假设n是一个5位数,我们就是要统计从第一位到第五位中,k可能出现的个数。

更具体一些,假设n=12345,k=3,m为当前统计到的位数(m=1,2,3,4,5),k出现的个数为cnt,如果我们要统计百位上3出现的次数,显然:
1. 小于3*100的数,我们不予考虑
2. 紧接我们考虑300~399的数
3. 再考虑1300~1399,2300~2399…9300~9399(共100*10=1000个数)
4. 最后考虑10300~10399,11300~11399,12300~12345中3出现个数(共100*2+46=246个数
从上面看到,只需固定前3位为300~399,直接算出后面位数所有可能出现的情况,就是我们对于当前位数出现的3的个数的统计。
比如在这里,就有1000+246=1246个数,恰好是
1 + 12345 % 100 + 12345 / 100 * 10
假设:

base = 100 (3位数最小值)
lower=12345 % 100 = 12345 % base
higher = 12345 / 100 * 10 = 12345 / base * 10
curBit = 3 = 12345 % (100 * 10) / 100 = 12345 % (base * 10) / base
则count = 1 + base * higer + lower;

则我们得到了计算当k=curBit时,k的个数(count)的大小

我们上面相关变量进行抽象:

1. higer:表示更高位,如当前位数为3,则更高位是第4、5位、
2. lower:表示更低位,如1、2位
3. curBit表示第3位的数字

我们可以类比分析出:

1. 当`k<curBit`,比如求第2位时,有`count = base * higer`
2. 当`k>curBit`,比如求第4位时,有` count = base * (higer + 1)`

,通过以上公式,就可以得到我们的解法了。

这里有两个特别需要注意的地方:
1. 如果k=n=0,则count=1
2. 如果k=0,n!=0,则我们应该不算最高位的情况,因为最高位不可能为0,综合以上情况,我们得到下面解法

算法实现如下:

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;
        int base = 1;
        int flag = 1;
        if(k == 0 && n == 0){
            return 1;
        }
        if(k == 0){
            flag = 10;
        }
        while(n / base >= flag){
            int curBit = n % (base*10) / base;
            int higer = n / (base*10);
            int lower = n % base;
            if(curBit < k){
                count += base * higer;
            }else if(curBit == k){
                count += 1 + base * higer + lower;
            }else{
                count += base * (higer + 1);
            }
            base *= 10;
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/qwe6112071/article/details/72510679