LintCode刷题之路(三):统计数字

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

思路:
设置5个变量:
cur : 当前位置的数字
before : 当前位置前的数字,如12345中4(十位)的before为123
after : 当前位置后的数字
count : 计数器
i : 目前在哪一位(个位、十位、百位…)

分五种情况:
1. n = 0且k=0 : 直接返回1
2. k=0且cur>k : 如果before!=0 count = count+before*i; 否则count = count+1
3. cur = k : count = count+before*i+after+1
4. cur>k : count = count+(before+1)*i
5. cur

C++:

class Solution {
public:
    /*
     * @param : An integer
     * @param : An integer
     * @return: An integer denote the count of digit k in 1..n
     */
    int digitCounts(int k, int n) {
        // write your code here
        int cur,before,after;
        int i = 1;
        int count = 0;

        if(n==0&&k==0)
        {
            return 1;
        }

        while(n/i>0)
        {
            cur = (n/i)%10;
            before = n/(i*10);
            after = n - (n/i)*i;

            if(k==0&&cur>k)
            {
                if(before!=0)
                {
                    count = count+before*i;
                }
                else
                {
                    count = count+before+1;
                }
            }
            else if(cur==k)
            {
                count = count+before*i+after+1;
            }
            else if(cur>k)
            {
                count = count+(before+1)*i;
            }
            else
            {
                count = count+before*i;
            }

            i = i*10;
        }

        return count;
    }
};

Py3:

class Solution:
    """
    @param: : An integer
    @param: : An integer
    @return: An integer denote the count of digit k in 1..n
    """

    def digitCounts(self, k, n):
        # write your code here
        count = 0
        i =1


        if n==0 and k==0:
            return 1

        while(n//i!=0):
            cur = (n//i)%10
            before = (n//i)//10
            after = n-(n//i)*i

            if k==0 and cur>k:
                if before!=0:
                    count = count+before*i
                else:
                    count = count+1
            elif cur==k:
                count = count+before*i+after+1
            elif cur>k:
                count = count+(before+1)*i
            else:
                count = count+before*i

            i = i*10

        return count

猜你喜欢

转载自blog.csdn.net/qq_38213612/article/details/80233777