您的位置:首页 > 其它

Leetcode:728. Self Dividing Numbers

2017-12-06 15:16 363 查看
问题重述:

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 = 22
Output: [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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: