Problem 728

Abstract / Summary

Find all numbers in a range that are divisible by each of their digits.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
14 lines | 405 bytes | submitted September 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 81% (400k+ submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 True is 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 from left up to and including right.
  • The conditional if isSelfDiv(n) filters out non-self-dividing numbers.
  • yield n produces 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 returns False. 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 left exceeds right, the range call yields no values, and the method produces an empty generator without error.
  • Single-Element Interval - When left equals right, 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 yield creates 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.
written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.93 | σ = 1.12

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
37 links | 23 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

1 easy 1 medium
3 solutions   September 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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