Advertisement

Self Dividing Numbers - LeetCode 728 Solution

Self Dividing Numbers - Complete Solution Guide

Self Dividing Numbers is LeetCode problem 728, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 , and 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 ). Example 1: Input: left = 1, right = 22 Output: [1,2,3,4,5,6,7,8,9,11,12,15,22] Example 2: Input: left = 47, right = 85 Output

Detailed Explanation

The problem asks us to find all self-dividing numbers within a given range [left, right] (inclusive). A self-dividing number is defined as a number that is divisible by every digit it contains. Additionally, a self-dividing number cannot contain the digit zero.

Solution Approach

The solution involves iterating through the numbers from 'left' to 'right'. For each number, we check if it's a self-dividing number. The checking is done by extracting each digit from the number. If a digit is zero or if the number is not divisible by the digit, the number is not self-dividing. If all digits pass the divisibility test, the number is added to the result list.

Step-by-Step Algorithm

  1. Step 1: Initialize an empty list (result) to store the self-dividing numbers.
  2. Step 2: Iterate through the numbers from 'left' to 'right' (inclusive).
  3. Step 3: For each number 'i', check if it's self-dividing.
  4. Step 4: To check if 'i' is self-dividing, extract each of its digits.
  5. Step 5: For each extracted digit, check if the digit is zero or if 'i' is not divisible by the digit. If either condition is true, 'i' is not self-dividing, and the inner loop is broken.
  6. Step 6: If all digits of 'i' divide 'i' without remainder and are not zero, 'i' is self-dividing. Append 'i' to the 'result' list.
  7. Step 7: After iterating through all numbers in the range, return the 'result' list.

Key Insights

  • Insight 1: The core idea is to iterate through the numbers in the given range and check each number for the self-dividing property.
  • Insight 2: To check if a number is self-dividing, we need to extract its digits and check if each digit divides the original number without any remainder and that each digit is non-zero.
  • Insight 3: Converting the integer to a string simplifies the digit extraction process in some languages like Python. In other languages like Java/C/C++, we use modulo and division operations to extract digits.

Complexity Analysis

Time Complexity: O(n*k)

Space Complexity: O(n)

Topics

This problem involves: Math.

Companies

Asked at: Epic Systems.