【剑指offer】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

二、解题思路 & 代码

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

复杂度分析:

  1. 时间复杂度 O(logn) : 循环内的计算操作使用 O(1) 时间;循环次数为数字 n 的位数,即 l o g 10 n log_{10}n ,因此循环使用 O(logn) 时间。
  2. 空间复杂度 O(1) : 几个变量使用常数大小的额外空间。

参考:

  1. LeetCode 题解

猜你喜欢

转载自blog.csdn.net/weixin_41888257/article/details/108008563