Similar Problems

Similar Problems not available

Self Dividing Numbers - Leetcode Solution

Companies:

LeetCode:  Self Dividing Numbers Leetcode Solution

Difficulty: Easy

Topics: math  

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, and 128 % 8 == 0.

Also, a self-dividing number is not allowed to contain the digit zero.

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

Example: Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]

Solution:

The brute force solution for the problem can be to iterate through each number between the given range and check if it is a self dividing number or not. If the number is a self-dividing number, we add it to the final output list. However, this solution will be very time-consuming and inefficient.

A better approach would be to optimize the solution by first checking if the single-digit numbers (1 to 9) are self-dividing or not. After that, instead of checking every single number, we can check for each digit in the range and ignore those that contain "0" or are not self-dividing.

Here are the steps to solve the problem:

Step 1: Create an empty list to store the result, let's call it 'result'.

Step 2: Check for the single-digit numbers 1 to 9, if they are self-dividing. If the number has only one digit, it is self-dividing as there is no denominator to check, so we append it to the result list.

Step 3: For the range between left and right, check each number. If a digit in the number is zero or the number is not self-dividing, ignore it and move to the next number. If all the digits of the number are self-dividing, then append it to the result list.

Step 4: Return the list 'result' as the final output.

The time complexity of this solution is O(nlogn), where n is the range between left and right.

Here's the code for the solution:

def selfDividingNumbers(left: int, right: int) -> List[int]: result = [] for i in range(left, right+1): digits = [int(d) for d in str(i)] if 0 in digits: continue if all(i % d == 0 for d in digits): result.append(i) return result

Test the function

print(selfDividingNumbers(1, 22))

Self Dividing Numbers Solution Code

1