[LeetCode]#728. Self Dividing Numbers

Fatboy Slim
2 min readMay 2, 2020

--

Environment: Python 3.7

Key technique: if not, //, %

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]

Analysis:

  1. Input numbers are divided by 10 to get remainder.
  2. If remainder =0 is first filter condition, delete 13, 14, 16.
  3. If not r is second filter condition, delete 10.
  4. Get answer.

Solution:

class Solution:
def selfDividingNumbers(self, left, right):
ans = []
for n in range(left, right + 1):
if self.isDividing(n):
ans.append(n)
return ans

def isDividing(self, num):
temp = num
while temp:
div = temp % 10
if not div or num % div != 0:
return False
temp //= 10
return True

Submission:

Reference:

https://blog.csdn.net/fuxuemingzhu/article/details/79053113

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet