LeetCode #233: Number of Digit One

来源:互联网 发布:淘宝上哪些店银是真的 编辑:程序博客网 时间:2024/05/21 15:43

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)
1 0
原创粉丝点击