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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章