LeetCode:233. 数字1的个数

1、题目描述

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。

示例:

输入: 13
输出: 6 
解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。

2、题解

2.1、解法一

class Solution(object):
    def count_one(self,end):
        l = [str(i) for i in range(end)]
        s = "".join(l)
        return s.count("1")

    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n == 0:
            return 0
        elif n <10:
            return self.count_one(n+1)
        m = 0
        tmp = n
        print("n:",n)
        while tmp//10:
            if tmp < 10:
                break
            m += 1
            tmp = tmp//10
        n = n - tmp * 10 ** m
        count = 0
        if tmp ==1:
            count += m*10**(m-1) +1 + n
        else:
            count = tmp*m*10**(m-1) + 10**m

        ret = self.countDigitOne(n)

        return ret+count

  

原文地址:https://www.cnblogs.com/bad-robot/p/10066340.html