Problem Statement
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
Analysis
Process from the rightmost digit to the leftmost digit and find the pattern.
Solution
class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
if n < 10:
return int(n > 0)
else:
res = 0
x, r, exp = n, 0, 0
while x:
d = x % 10
cnt = exp * pow(10, exp - 1) + 1
if d == 1:
res = cnt + res + r
if d > 1:
res = res + (cnt - 1) * d + pow(10, exp)
r += d * pow(10, exp)
exp += 1
x /= 10
return int(res)