#728
Self Dividing Numbers
EasyMathMathIteration
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * d) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * d)Space O(n)
The optimal solution still checks each number in the range, but it uses a more efficient method to validate self-dividing status by directly manipulating digits without converting to strings, which can save time.
⚙️
Algorithm
6 steps- 1Step 1: Initialize an empty list to store self-dividing numbers.
- 2Step 2: Loop through each number from left to right.
- 3Step 3: For each number, use a while loop to extract each digit.
- 4Step 4: Check if the digit is zero or does not divide the number evenly.
- 5Step 5: If all digits pass the checks, add the number to the list.
- 6Step 6: Return the list of self-dividing numbers.
solution.py19 lines
1# Full working Python code
2
3def selfDividingNumbers(left, right):
4 result = []
5 for num in range(left, right + 1):
6 n = num
7 is_self_dividing = True
8 while n > 0:
9 digit = n % 10
10 if digit == 0 or num % digit != 0:
11 is_self_dividing = False
12 break
13 n //= 10
14 if is_self_dividing:
15 result.append(num)
16 return result
17
18# Example usage
19print(selfDividingNumbers(1, 22))ℹ
Complexity note: The time complexity is O(n * d), where n is the number of integers in the range and d is the number of digits in the largest number (at most 5 for numbers up to 10,000). The space complexity is O(n) due to the storage of results.
- 1Self-dividing numbers cannot contain the digit zero.
- 2Each digit must divide the number evenly for it to be considered self-dividing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.