剑指 Offer 43. 1~n 整数中 1 出现的次数

Posted 风去幽墨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指 Offer 43. 1~n 整数中 1 出现的次数相关的知识,希望对你有一定的参考价值。

题目链接:

https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/

题意:

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

题解:

数学解法:
记录每个数位上1可能出现的次数,最后求和即可。
分三种情况:(记当前位的数字为cur,高位为high,低位为low,digit为当前数字占的位置的基数,例如1234,假设分析十位上的1出现的次数时cur为3,high为12,low为4,digit为10)

  • cur == 0:high*digit,由0至高位最大值-1,且低位可随意变化故要乘上digit。
  • cur == 1:high*digit+low+1,由0至高位最大值-1,且低位可随意变化,当高位为最高时,低位有限制。
  • cur > 1:(high+1)*digit,由0至高位最大值,且低位无限制。

代码:

class Solution:
    def countDigitOne(self, n: int) -> int:
        digit, res = 1, 0
        high, cur, low = n // 10, n % 10, 0
        while high != 0 or cur != 0:
            if cur == 0: res += high * digit
            elif cur == 1: res += high * digit + low + 1
            else: res += (high + 1) * digit
            low += cur * digit
            cur = high % 10
            high //= 10
            digit *= 10
        return res

以上是关于剑指 Offer 43. 1~n 整数中 1 出现的次数的主要内容,如果未能解决你的问题,请参考以下文章

每日一题 - 剑指 Offer 43. 1~n整数中1出现的次数

剑指 Offer 43. 1~n 整数中 1 出现的次数

剑指offer其他算法43. 1~n整数中1出现的次数

剑指offer-面试题43-1~n整数中1出现的次数-归纳法

LeetCode(剑指 Offer)- 43. 1~n 整数中 1 出现的次数

LeetCode(剑指 Offer)- 43. 1~n 整数中 1 出现的次数