Skip to content

Commit 28ae35f

Browse files
committed
Number of Digit One
1 parent 07e6ec5 commit 28ae35f

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

233 Number of Digit One.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'''
2+
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
3+
4+
For example:
5+
Given n = 13,
6+
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
7+
'''
8+
9+
class Solution(object):
10+
def countDigitOne(self, n):
11+
"""
12+
:type n: int
13+
:rtype: int
14+
"""
15+
x, m, count = n, 1, 0
16+
while x > 0:
17+
lastDigit = x % 10
18+
x //= 10
19+
count += x * m
20+
if lastDigit == 1:
21+
count += n % m + 1
22+
elif lastDigit > 1:
23+
count += m
24+
m *= 10
25+
return count
26+
27+
28+
if __name__ == "__main__":
29+
assert Solution().countDigitOne(13) == 6

0 commit comments

Comments
 (0)