Lintcode 3. 统计数字

来源:互联网 发布:mac改变用户名 编辑:程序博客网 时间:2024/05/21 06:03

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

分析:看到上面题目的第一想法是按位挨个进行统计,由低位到高位,将k与当前位的数字进行比较,分类讨论。另外还要注意一些特殊情况,比如k == 0 且当前为最高位数字的情况

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        i = 1        t = 10**i        count = 0         while int(n/(t/10)):                #n不为0的情况            num_cur = (n % t - n % (t / 10)) / (t / 10)            if int(n/t) != 0 or (int(n/t) == 0 and k != 0):                if k == num_cur:                    count += int(n / t)*(t / 10) + n % (t/10) + 1                elif k < num_cur:                    count += int(n / t)*(t / 10) + t / 10                else:                    count += int(n / t)*(t / 10)            else:                                #k == 0且当前为最高位数字                if i == 1:                       #最高位为个位                    count = 1            i = i + 1            t = 10**i        if n == 0 and k == 0:            count = 1        return int(count)