leetcode 728. Self Dividing Numbers ( Python )

描述

A self-dividing number is a number that is divisible by every digit it contains.php

For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.ios

Also, a self-dividing number is not allowed to contain the digit zero.git

Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.微信

Example 1:app

Input: 
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
复制代码

Note:less

The boundaries of each input argument are 1 <= left <= right <= 10000.
复制代码

解析

根据题意,直接暴力破解,能够看出这个题就是遍历一个包含非 0 的数字中的每一个数字,若是都能整除就能够保留,提早判断条件,不符合就直接跳过,这样能节省很多时间。时间复杂度最少为 O(N),一般时间复杂度为 O(NlogM),空间复杂度为 O(N)。yii

解答

class Solution(object):
def selfDividingNumbers(self, left, right):
    """
    :type left: int
    :type right: int
    :rtype: List[int]
    """
    result= []
    for i in range(left,right+1):
        count = 0
        for s in str(i):
            if s=='0' or i%int(s)!=0:
                break
            else:
                count+=1
                continue
        if count == len(str(i)):
            result.append(i)
    return result        	      
复制代码

运行结果

Runtime: 40 ms, faster than 76.40% of Python online submissions for Self Dividing Numbers.
Memory Usage: 11.9 MB, less than 56.13% of Python online submissions for Self Dividing Numbers.
复制代码

每日格言:不要慨叹生活底痛苦!慨叹是弱者 —— 高尔基svg

请做者喝杯水
支付宝

支付宝

微信

微信
相关文章
相关标签/搜索