Self Dividing Numbers — LeetCode 728 Python Solution
- Problem
- #728
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- left = 1, right = 22
- Output
- [1,2,3,4,5,6,7,8,9,11,12,15,22]
Python solution
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def check(x: int) -> bool:
y = x
while y:
if y % 10 == 0 or x % (y % 10):
return False
y //= 10
return True
return [x for x in range(left, right + 1) if check(x)]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log_{10} M), where n is the number of elements in the interval [\textit{left}, \textit{right}], and M = \textit{right}, which is the maximum value in the interval |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 728. Self Dividing Numbers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 728. Self Dividing Numbers?
- LeetCode 728. Self Dividing Numbers is rated Easy on LeetCode.
- What is the time complexity of LeetCode 728. Self Dividing Numbers?
- The Python solution on this page runs in O(n \times \log_{10} M), where n is the number of elements in the interval [\textit{left}, \textit{right}], and M = \textit{right}, which is the maximum value in the interval.
- What is the space complexity of LeetCode 728. Self Dividing Numbers?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 728. Self Dividing Numbers cover?
- LeetCode 728. Self Dividing Numbers is tagged Math on LeetCode.