Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
728. 自除数 - 力扣(LeetCode) (leetcode-cn.com)
自除数 是指可以被它包含的每一位数整除的数。
- 例如,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 <= 10^4
二、思路分析:
- 遍历left-right包含的数字,设置空数组用来存储自除数
- 将数字转为字符串判断字符串中是否有'0',若有则直接跳过该数字
- 不含0则对该数字每位进行除余判断,若不为0直接跳过该数字,若为0则进行判断直到每位判断完成,最后添加进数组
- 全部遍历完成后输出数组
三、AC 代码:
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
out_list=[]
for i in range(left,right+1):
flag = 1
chars = str(i)
if '0' in chars:
continue
for char in chars:
if i % int(char) == 0:
continue
else:
flag =0
break
if flag ==1:
out_list.append(i)
return out_list
范文参考:
【728. 自除数】题解:暴力法 - 自除数 - 力扣(LeetCode) (leetcode-cn.com)
Python3 正常思路超短解法详解 与 花样一行法 - 自除数 - 力扣(LeetCode) (leetcode-cn.com)