Python 0728.py
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def isSelfDiv(n):
for c in str(n):
if c == "0":
return False
if n % int(c) != 0:
return False
return True
for n in range(left, right+1):
if isSelfDiv(n):
yield n
Difficulty
and has an acceptance rate of about 81% (400k+ submissions).
Typical patterns to solve this problem:
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a method selfDividingNumbers. This method enumerates all self-dividing numbers within a closed interval [left, right]. A self-dividing number is an integer that is divisible by each of its non-zero decimal digits. The method uses an inner helper isSelfDiv to test the property and yields qualifying numbers one by one, making the result a lazy sequence.
Core Logic
Helper Function isSelfDiv
The helper determines whether a single integer satisfies the self-dividing condition.
def isSelfDiv(n):
for c in str(n):
if c == "0":
return False
if n % int(c) != 0:
return False
return True
- The number is converted to its string representation, allowing iteration over each character
c. - Encountering a
'0'digit immediately disqualifies the number because division by zero is undefined. - For any other digit, the function checks
n % int(c). A non-zero remainder indicates the digit does not divide the number, causing an early exit. - If the loop completes without triggering a return, the number passes all checks and
Trueis returned.
Main Loop and Yielding Results
The outer method iterates through the interval and yields numbers that satisfy the helper predicate.
for n in range(left, right + 1):
if isSelfDiv(n):
yield n
range(left, right + 1)generates each integer fromleftup to and includingright.- The conditional
if isSelfDiv(n)filters out non-self-dividing numbers. yield nproduces each qualifying number as part of a generator, enabling on-demand consumption.
Edge Cases Handled
- Zero Digits - The helper explicitly checks for the character
'0'and returnsFalse. This prevents attempts to divide by zero and correctly excludes numbers containing a zero digit. - Early Termination - As soon as a disqualifying digit is found, the function returns
False. This avoids unnecessary checks for the remaining digits, handling cases where the first digit already invalidates the number. - Empty Interval - If
leftexceedsright, therangecall yields no values, and the method produces an empty generator without error. - Single-Element Interval - When
leftequalsright, the loop runs exactly once, correctly evaluating that single number.
Performance Optimizations
- Early Exit Strategy - By returning immediately upon encountering a zero digit or a non-divisible digit, the algorithm minimizes the number of modulus operations, especially for numbers with many digits.
- Lazy Generation - Using
yieldcreates a generator rather than building a list of results. This reduces memory consumption because only one number is held in memory at a time during iteration. - String Conversion for Digit Access - Converting the integer to a string provides a straightforward way to access each digit without performing repeated arithmetic (e.g., repeated division and modulo by 10). This keeps the inner loop concise and efficient for the typical range of input values.
ELI5 - Simplified Explanation
Imagine you have a big box of numbered blocks. Some of these numbers are very special because they are made of smaller pieces that can divide the whole number perfectly without leaving any leftovers.
Think of it like sharing cookies. If a number is made of the digits one, two, and four, it means the whole number must be able to be split evenly by one, by two, and by four. If the number has a zero in it, that number is not allowed to play this game because you cannot share cookies with nobody.
The code starts by looking at every single number in a line, starting from the first number you give it and going all the way to the last one. For every number in that line, it picks it up and checks its digits one by one. It looks at each digit, turns it back into a number, and checks if the big number can be divided by that digit without any remainder. If it finds a zero or if the math does not work out perfectly, it decides the number is not special.
When it finds a number that passes the test, it places that number into a new pile of special numbers. It keeps doing this until it reaches the very last number in the line, and then it is all done.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 507: Perfect Number
- problem 2283: Check if Number Has Equal Digit Count and Digit Value
- problem 2520: Count the Digits That Divide a Number
Solved On The Same Day
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality