《剑指Offer》刷题笔记——面试题43. 1~n整数中1出现的次数

难度:中等/困难

一、题目描述:

在这里插入图片描述

二、解题分析:

1、leetcode解析

在这里插入图片描述

2、代码实现

class Solution(object):
    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 1:
            return 0
        if n < 10:
            return 1
        
        # t需要能被10整除
        def countPart(t):      
            if t == 10:
                return 1            
            s = t/10
            return 10 * countPart(t/10) + s
        ans = 0        
        # 判断n是几位数,如n=388,l就是100
        y = 10
        while y <= n:
            y *= 10
        l = y / 10
        subn = n % l
        ans += self.countDigitOne(subn)
        c = n / l        
        ans += c * countPart(l) + (l if c != 1 else subn+1) # 这里要注意下以1开头的情况
        return ans
发布了132 篇原创文章 · 获赞 154 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_34108714/article/details/104720780