Number of Digit One LeetCode solution in Python

1
# Runtime: 65 ms (Top 7.05%) | Memory: 13.8 MB (Top 68.36%)
2
class Solution:
3
def countDigitOne(self, n: int) -> int:
4
num = str(n)[::-1]
5
count = 0
6
for i in range(len(num) - 1, -1, -1):
7
pv = 10**i # placevalue
8
# mulitplicity of current digit (how many times it will be repeated)
9
mul = n // (pv * 10)
10
rem = n % pv # remainder of current place value
11
count += (
12
mul * pv
13
) # count for number of times 1 occurs in this place when the current digit is considered to be less than 1
14
# if the current digit is greater than 1 then additional number of 1's are added to the count (equivalent to the place value)
15
if num[i] > "1":
16
count += pv
17
# if the current digit is equal to 1 then additional number of 1's are added to the count (equivalent to the number modded by the current place value)
18
if num[i] == "1":
19
count += rem + 1
20
return count

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0