1. 程式人生 > >LeetCode:233. 數字1的個數

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