【leetcode】233. Number of Digit One

博客围绕给定整数n,计算小于等于n的所有非负整数中数字1出现的总个数这一问题展开。给出解题思路,称其为《编程之美》上的题目,还给出了相关代码,代码转载自特定博客。

题目如下:

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

Example:

Input: 13
Output: 6 
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

解题思路:本题是《编程之美》上的题目,详细分析如下图。

代码如下:

class Solution(object):
    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 0:
            return 0
        res = 0
        sn = str(n)
        length = len(sn)
        inx = len(sn) - 1
        while inx >= 0:
            lower = sn[inx+1:]
            current = sn[inx]
            higher = sn[:inx]
            if int(current) == 0:
                if len(higher) > 0:
                    res += int(higher) * (10 ** (length - inx - 1))
            elif int(current) == 1:
                if len(higher) > 0:
                    res += int(higher) * (10 ** (length - inx - 1))
                if len(lower) > 0:
                    res += int(lower)
                res += 1

            else:
                if len(higher) > 0:
                    res += (int(higher))  * (10 ** (length - inx - 1))
                res += 1 * (10 ** (length - inx - 1))
            inx -= 1
        return res

 

转载于:https://www.cnblogs.com/seyjs/p/10943714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值