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

請做者喝杯水
支付寶

支付寶

微信

微信
相關文章
相關標籤/搜索