Skip to content

Commit 0955cdb

Browse files
authored
Create digit-count-in-range.py
1 parent 0febfd3 commit 0955cdb

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Python/digit-count-in-range.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time: O(logn)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def digitsCount(self, d, low, high):
6+
"""
7+
:type d: int
8+
:type low: int
9+
:type high: int
10+
:rtype: int
11+
"""
12+
def digitsCount(n, k):
13+
pivot, result = 1, 0
14+
while n >= pivot:
15+
result += (n//(10*pivot))*pivot + \
16+
min(pivot, max(n%(10*pivot) - k*pivot + 1, 0))
17+
if k == 0:
18+
result -= pivot
19+
pivot *= 10
20+
return result+1
21+
22+
return digitsCount(high, d) - digitsCount(low-1, d)

0 commit comments

Comments
 (0)