Number of Digit One
Problem: Number of Digit One
Code in Python:
class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
if n < 0: return 0
count, num, base, highBase = 0, n, 1, 10
while num:
num, mod = divmod(num, 10)
if mod == 0: count += (n / highBase) * base
elif mod == 1: count += (n / highBase) * base + (n % base + 1)
else: count += (n / highBase + 1) * base
base *= 10
highBase *= 10
return count