Approach #1: Brute Force [Accepted]

Intuition and Algorithm

For each number in the given range, we will directly test if that number is self-dividing.

By definition, we want to test each whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128 % d == 0 for d = 1, 2, 8. To do that, we need to iterate over each digit of the number.

A straightforward approach to that problem would be to convert the number into a character array (string in Python), and then convert back to integer to perform the modulo operation when checking n % d == 0.

We could also continually divide the number by 10 and peek at the last digit. That is shown as a variation in a comment.

Complexity Analysis

  • Time Complexity: , where is the number of integers in the range , and assuming is bounded. (In general, the complexity would be .)

  • Space Complexity: , the length of the answer.

Analysis written by: @awice.