LeetCode---数字1的个数

题目:给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。

示例:

输入: 13
输出: 6 
解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。
#直接了当的当做一个数字参与运算,一个位数一个位数(个十百千万)的提取-->判断

class Solution:
    def countDigitOne(self, n: 'int') -> 'int':
        count=0
        for i in range(1,n+1):
            #print(i)
            while i:
                if i%10==1:
                    count+=1
                    # print('i=',i)
                    # print('count=',count)
                    #break
                i//=10
        return count

s=Solution()
s.countDigitOne(13)

LeetCode---数字1的个数

方法二:

#把输入的int数字当做一个string字符串类型,要判断的数字1也当做string类型“1”;这样就是判断每一个字符是否一样

class Solution:
    def countDigitOne(self, n: 'int') -> 'int':
        total= 0 
        for i in range(1,n+1):
            total+=list(str(i)).count('1')
        return total
s = Solution()
s.countDigitOne(13)

:看到有人在争论,不小心看成了“给定一个整数 n,计算所有小于等于 n 的非负整数中含有数字 1 出现的数的个数。”

然后就成了1, 10, 11, 12, 13 ,5个数字,答案为5;不一样的地方就是一个对数字中所有位数的数字都检查下,另一个是只要检查到有1存在,就+1不再检查了,break跳出。如下所示:

class Solution:
    def countDigitOne(self, n: 'int') -> 'int':
        count=0
        for i in range(1,n+1):
            #print(i)
            while i:
                if i%10==1:
                    count+=1
                    # print('i=',i)
                    # print('count=',count)
                    break
                i//=10
        return count

s=Solution()
s.countDigitOne(13)

LeetCode---数字1的个数

欢迎关注:小白算法,公众号,一个人人都能懂的知识公众平台

LeetCode---数字1的个数