首页 > 其他分享 >leetcode 728. Self Dividing Numbers

leetcode 728. Self Dividing Numbers

时间:2023-05-30 18:04:00浏览次数:33  
标签:right return Dividing dividing Self self num leetcode left

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.

 

解法1:

养成好习惯,一定要先写测试用例,然后写下伪代码,最后才是代码!切忌直接上代码!

ans = []

for num In range(left, right+1):

  for each bit in num:

          check num % bit == 0?

      if all bit div is 0 then add num to ans

class Solution(object):
    def selfDividingNumbers(self, left, right):
        """
        :type left: int
        :type right: int
        :rtype: List[int]
        [1, 2, 3, 4, 5, 6, 7, 8, 9]
        [11, 12, 15] 10/1,2,5
        [22=2*11, 24=2*2*2*3] 20/2,4,
        [33, 35, 36] 30/3,5,6
        [44, 45, 48] 40/4,5,8
        ...
        [99]
        [111, 112, 115] 110/?
        [122, 124]
        abcd =
        (a*1000+b*100+c*10+d)%a=0
        (a*1000+b*100+c*10+d)%b=0
        (a*1000+b*100+c*10+d)%c=0
        (a*1000+b*100+c*10+d)%d=0
        """
        ans = []
        for i in range(left, right+1):
            if self.is_div_num(i):
                ans.append(i)
        return ans
    
    def is_div_num(self, n):
        if n == 0:
            return False
        q = n
        while q:
            c = q % 10
            if (c == 0) or (n % c != 0):
                return False           
            q /= 10
        return True

 

改进版本:

class Solution(object):
    def selfDividingNumbers(self, left, right):
        is_self_dividing = lambda num: '0' not in str(num) and all(num % int(digit) == 0 for digit in str(num))
        return filter(is_self_dividing, range(left, right + 1))

关于all:

>>> all([1,2,3])
True
>>> all([1,2,0])
False

官方解法:

class Solution(object):
    def selfDividingNumbers(self, left, right):
        def self_dividing(n):
            for d in str(n):
                if d == '0' or n % int(d) > 0:
                    return False
            return True
        """
        Alternate implementation of self_dividing:
        def self_dividing(n):
            x = n
            while x > 0:
                x, d = divmod(x, 10)
                if d == 0 or n % d > 0:
                    return False
            return True
        """
        ans = []
        for n in range(left, right + 1):
            if self_dividing(n):
                ans.append(n)
        return ans #Equals filter(self_dividing, range(left, right+1))
python2/3 one-liner:

[x for x in range(left, right+1) if all(y and not x%y for y in map(int,str(x)))]>>> map(int, ["12","23"])
[12, 23]

标签:right,return,Dividing,dividing,Self,self,num,leetcode,left
From: https://blog.51cto.com/u_11908275/6381153

相关文章

  • leetcode 657. Judge Route Circle
    Initially,thereisaRobotatposition(0,0).Givenasequenceofitsmoves,judgeifthisrobotmakesacircle,whichmeansitmovesbackto theoriginalplace.Themovesequenceisrepresentedbyastring.Andeachmoveisrepresentbyacharacter.The......
  • leetcode 461. Hamming Distance
    The Hammingdistance betweentwointegersisthenumberofpositionsatwhichthecorrespondingbitsaredifferent.Giventwointegers x and y,calculatetheHammingdistance.Note:0≤ x, y <231.Example:Input:x=1,y=4Output:2Explanation:1......
  • leetcode 771. Jewels and Stones
    You'regivenstrings J representingthetypesofstonesthatarejewels,and S representingthestonesyouhave. Eachcharacterin Sisatypeofstoneyouhave. Youwanttoknowhowmanyofthestonesyouhavearealsojewels.Thelettersin J areg......
  • leetcode 378. Kth Smallest Element in a Sorted Matrix
    Givenanxnmatrixwhereeachoftherowsandcolumnsaresortedinascendingorder,findthekthsmallestelementinthematrix.Notethatitisthekthsmallestelementinthesortedorder,notthekthdistinctelement.Example:matrix=[[1,5,9......
  • leetcode 617. Merge Two Binary Trees
    Giventwobinarytreesandimaginethatwhenyouputoneofthemtocovertheother,somenodesofthetwotreesareoverlappedwhiletheothersarenot.Youneedtomergethemintoanewbinarytree.Themergeruleisthatiftwonodesoverlap,thensumn......
  • leetcode 257. Binary Tree Paths
    Givenabinarytree,returnallroot-to-leafpaths.Forexample,giventhefollowingbinarytree: 1/\23\5Allroot-to-leafpathsare:["1->2->5","1->3"]#Definitionforabinarytreenode.#classTreeNode(obje......
  • leetcode 202. Happy Number
    Writeanalgorithmtodetermineifanumberis"happy".Ahappynumberisanumberdefinedbythefollowingprocess:Startingwithanypositiveinteger,replacethenumberbythesumofthesquaresofitsdigits,andrepeattheprocessuntilthe......
  • leetcode 671. Second Minimum Node In a Binary Tree
    Givenanon-emptyspecialbinarytreeconsistingofnodeswiththenon-negativevalue,whereeachnodeinthistreehasexactlytwoorzerosub-node.Ifthenodehastwosub-nodes,thenthisnode'svalueisthesmallervalueamongitstwosub-nodes.G......
  • leetcode 409. Longest Palindrome
    Givenastringwhichconsistsoflowercaseoruppercaseletters,findthelengthofthelongestpalindromesthatcanbebuiltwiththoseletters.Thisiscasesensitive,forexample"Aa"isnotconsideredapalindromehere.Note:Assumethelength......
  • leetcode 747. Largest Number At Least Twice of Others
    Inagivenintegerarraynums,thereisalwaysexactlyonelargestelement.Findwhetherthelargestelementinthearrayisatleasttwiceasmuchaseveryothernumberinthearray.Ifitis,returntheindexofthelargestelement,otherwisereturn-1.Ex......