Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
number-of-digit-one.py 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-06-02 21:15 +08:00 . Update number-of-digit-one.py
# Time: O(logn)
# Space: O(1)
class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
pivot, result = 1, 0
while n >= pivot:
result += (n//(10*pivot))*pivot + \
min(pivot, max(n%(10*pivot) - pivot + 1, 0))
pivot *= 10
return result
# Time: O(logn)
# Space: O(1)
class Solution2(object):
# @param {integer} n
# @return {integer}
def countDigitOne(self, n):
k = 1
cnt, multiplier, left_part = 0, 1, n
while left_part > 0:
# split number into: left_part, curr, right_part
curr = left_part % 10
right_part = n % multiplier
# count of (c000 ~ oooc000) = (ooo + (k < curr)? 1 : 0) * 1000
cnt += (left_part / 10 + (k < curr)) * multiplier
# if k == 0, oooc000 = (ooo - 1) * 1000
if k == 0 and multiplier > 1:
cnt -= multiplier
# count of (oook000 ~ oookxxx): count += xxx + 1
if curr == k:
cnt += right_part + 1
left_part /= 10
multiplier *= 10
return cnt
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助