We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Self Dividing Numbers

Number: 728

Difficulty: Easy

Paid? No

Companies: Epic Systems, Meta


Problem Description

A self-dividing number is a number that is divisible by every digit it contains. Notably, a number cannot be self-dividing if it contains the digit zero. Given two integers left and right, the task is to return a list of all self-dividing numbers in the inclusive range [left, right].


Key Insights

  • Iterate through each number in the range [left, right].
  • For each number, check if every digit (ignoring numbers with digit zero) divides the number evenly.
  • Use a helper function to assess if a given number is self-dividing.
  • The problem constraints allow for a brute-force approach since the range is small (up to 10^4).

Space and Time Complexity

Time Complexity: O(n * d), where n is the number of integers in the range and d is the number of digits in each number (d is small, typically <= 5). Space Complexity: O(1), aside from the output list.


Solution

The solution involves iterating over every number between left and right. For each number, convert the number to its individual digits and check whether each digit (except zero) divides the number without leaving a remainder. If a digit is zero or doesn't divide the number evenly, skip that number. Otherwise, add it to the result list. The main tools used are loops, modulo operations for divisibility, and simple condition checking.


Code Solutions

# Function to check if a number is self-dividing
def is_self_dividing(num):
    original_num = num
    while num > 0:
        digit = num % 10  # Extract the last digit
        if digit == 0 or original_num % digit != 0:  # Digit is 0 or does not evenly divide original_num
            return False
        num //= 10  # Remove the last digit
    return True

def selfDividingNumbers(left, right):
    result = []
    for num in range(left, right + 1):  # Iterate through all numbers in the given range
        if is_self_dividing(num):
            result.append(num)  # Append if the number is self-dividing
    return result

# Example usage:
print(selfDividingNumbers(1, 22))
← Back to All Questions