43. 1 ~ n 整数中 1 出现的次数【难】


comments: true
difficulty: 中等
edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9%A2%9843.%201%EF%BD%9En%E6%95%B4%E6%95%B0%E4%B8%AD1%E5%87%BA%E7%8E%B0%E7%9A%84%E6%AC%A1%E6%95%B0/README.md

面试题 43. 1 ~ n 整数中 1 出现的次数

题目描述

输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。

例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。

示例 1:

输入:n = 12
输出:5

示例 2:

输入:n = 13
输出:6

限制:

  • 1 <= n < 2^31

注意:本题与主站 233 题相同:https://leetcode.cn/problems/number-of-digit-one/

解法

【LeetCode力扣刷题 | 剑指Offer题解合集 | 画解算法思路Python3或C++代码实现】 https://www.bilibili.com/video/BV1CK411c7gx/?p=38&share_source=copy_web&vd_source=ed4a51d52f6e5c9a2cb7def6fa64ad6a 【讲的很清晰】
在这里插入图片描述

时间复杂度 O ( log ⁡ n ) O(\log n) O(logn)

Python3
class Solution:
    def countDigitOne(self, n: int) -> int:
  def count_digit_one(n):
    base = 1
    res = 0
    while base <= n:
        b = n // base
        a = n // (base * 10)
        cur = (n // base) % 10
        
        if cur > 1:
            res += (a + 1) * base
        elif cur == 1:
            res += a * base + (n % base) + 1
        else:
            res += a * base
        
        base *= 10
    
    return res
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值