Leetcode笔记 每日一题 728. 自除数 (22.03.31)
Leetcode 每日一题 728. 自除数 (22.03.31)
题目
自除数 是指可以被它包含的每一位数整除的数。
- 例如,128 是一个 自除数 ,因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。
自除数 不允许包含 0 。
给定两个整数 left
和 right
,返回一个列表,列表的元素是范围 [left, right]
内所有的自除数 。
示例 1:
输入:left = 1, right = 22
输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
示例 2:
输入:left = 47, right = 85
输出:[48,55,66,77]
提示:
1 <= left <= right <= 104
解题思路
遍历[left , right],然后将每一个数
i
用str()
函数转换成字符串形式,进行读取每个数的每一位数j
,最后进行判断j == '0' or i % int(j) :
- 如果不成立便将数字
i
存入数组res[]
中
Python代码
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
res = []
for i in range(left , right+1):
result = True
for j in str(i):
if j == '0' or i % int(j) :
result = False
if result:
res.append(i)
return res
官方题解
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def isSelfDividing(num: int) -> bool:
x = num
while x:
x, d = divmod(x, 10)
if d == 0 or num % d:
return False
return True
return [i for i in range(left, right + 1) if isSelfDividing(i)]