Self Dividing Numbers - 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
  • 128 % 8 == 0

A self-dividing number is not allowed to contain the digit zero.

Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right] (both inclusive).

Input & Output

Example 1 — Basic Range
$ Input: left = 1, right = 22
Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]
💡 Note: Numbers like 10, 20 contain zero (invalid). 13: 13%3=1≠0 (invalid). 22: 22%2=0 ✓ (valid)
Example 2 — Three-Digit Numbers
$ Input: left = 47, right = 85
Output: [48,55,66,77]
💡 Note: 48: 48%4=0, 48%8=0 ✓. 55: 55%5=0 ✓. 66: 66%6=0 ✓. 77: 77%7=0 ✓
Example 3 — Single Number Range
$ Input: left = 128, right = 128
Output: [128]
💡 Note: 128: 128%1=0, 128%2=0, 128%8=0, all digits divide evenly

Constraints

  • 1 ≤ left ≤ right ≤ 104

Visualization

Tap to expand
Self Dividing Numbers Mathematical Digit Extraction Approach INPUT Number Range [left, right] left 1 right 22 Numbers to Check: 1 22 Self-Dividing Rule: Number divisible by ALL its digits 128 % 1 == 0 [OK] 128 % 2 == 0 [OK] No zeros allowed in digits! 10, 20 --> invalid ALGORITHM STEPS 1 Loop through range for n = left to right 2 Extract each digit digit = n % 10, n = n / 10 3 Check divisibility if digit==0 or n%digit!=0 4 Add if valid Add n to result list Example: Check 12 12 % 10 = 2 (digit) 12 % 2 == 0 [OK] 12 / 10 = 1 (next) 12 % 1 == 0 [OK] 12 is self-dividing! 13: 13 % 3 != 0 --> skip FINAL RESULT Self-Dividing Numbers Found: 1 2 3 4 5 6 7 8 9 11 12 15 22 Output Array: [1,2,3,4,5,6,7,8,9,11,12,15,22] Statistics Total checked: 22 Self-dividing: 13 Rejected: 9 (10,13,14...) Key Insight: Mathematical digit extraction using modulo (%) and division (/) avoids string conversion overhead. For each number n: extract last digit with n%10, check divisibility, then n=n/10 to get next digit. Time: O(n*d) where n=range size, d=avg digits. Space: O(1) excluding output. Early exit on zero digit or failure. TutorialsPoint - Self Dividing Numbers | Mathematical Digit Extraction Approach
Asked in
Amazon 15 Google 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
986 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen