Leetcode:728. Self Dividing Numbers

来源:互联网 发布:java中的方法 编辑:程序博客网 时间:2024/05/29 10:08

问题重述:

A self-dividing number is a number that is divisible by every digit it contains.For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.Also, a self-dividing number is not allowed to contain the digit zero.Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.Example 1:Input: left = 1, right = 22Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]Note:The boundaries of each input argument are 1 <= left <= right <= 10000.

考虑到时间复杂度的优化应该少用for循环,利用python中参数类型强制转换,且str类型是可迭代类型:

for digit in str(num))

遍历digit寻找全部符合要求的非零数字,采用filter()函数来代替fo,filter的用法见:http://blog.csdn.net/SeeTheWorld518/article/details/46975897,简化代码:

def selfDividingNumbers(left, right):    dividing = lambda num: '0' not in str(num) and all(num % int(digit) == 0 for digit in str(num))    return filter(dividing, range(left, right + 1))
原创粉丝点击