algoadvance

A self-dividing number is a number that is divisible by every digit it contains.

Given a lower and upper number bound, output a list of every possible self-dividing number, including the bounds if possible.

You can assume that the input boundaries are always valid.

Clarifying Questions

  1. Range Inclusion: Should the range include the lower and upper bounds?
    • Yes, include the lower and upper bounds.
  2. Zero Handling: How to handle numbers with zero in their digits?
    • Numbers containing any zero digit are not self-dividing numbers.
  3. Output Order: Should the output list be in any specific order?
    • The output list should be in ascending order since we will be iterating through the range in increasing order.

Strategy

  1. Helper Function: Create a helper function is_self_dividing to check if a number is self-dividing.
    • Convert the number to its digit representation.
    • If any digit is 0 or the number is not divisible by any of its digits, return False.
    • Otherwise, return True.
  2. Iterate Range: Iterate through the given range (inclusive) and collect all numbers that satisfy the self-dividing property using the helper function.
  3. Collect Results: Return the list of self-dividing numbers.

Code

Here is the Python code to solve the problem:

def is_self_dividing(number):
    original = number
    while number > 0:
        digit = number % 10
        if digit == 0 or original % digit != 0:
            return False
        number //= 10
    return True

def selfDividingNumbers(left, right):
    result = []
    for num in range(left, right + 1):
        if is_self_dividing(num):
            result.append(num)
    return result

# Test the function
left = 1
right = 22
print(selfDividingNumbers(left, right))

Time Complexity

In summary:

Try our interview co-pilot at AlgoAdvance.com