LeetCode 728: Self Dividing Numbers Solution
Master LeetCode problem 728 (Self Dividing Numbers), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
728. Self Dividing Numbers
Problem Explanation
Explanation
To solve this problem, we iterate through each number in the range [left, right] and check if it is a self-dividing number. For each number, we check if it is divisible by all its digits without containing the digit 0. We can implement this by converting the number to a string and iterating through each digit to perform the divisibility check. If a number is self-dividing, we add it to the result list.
Algorithm:
- Initialize an empty list to store the self-dividing numbers.
- Iterate through each number in the range [left, right]:
- For each number, convert it to a string.
- Iterate through each digit in the number:
- Check if the digit is 0 or if the number is not divisible by the digit. If either condition is true, break out of the loop.
- If all digits are checked and the number is self-dividing, add it to the result list.
- Return the list of self-dividing numbers.
Time Complexity
The time complexity of this algorithm is O(D * N), where D is the maximum number of digits in any number in the range and N is the count of numbers in the range [left, right].
Space Complexity
The space complexity is O(N) to store the list of self-dividing numbers.
Solution Code
class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> result = new ArrayList<>();
for (int i = left; i <= right; i++) {
if (isSelfDividing(i)) {
result.add(i);
}
}
return result;
}
private boolean isSelfDividing(int num) {
String numStr = String.valueOf(num);
for (char c : numStr.toCharArray()) {
if (c == '0' || num % (c - '0') != 0) {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 728 (Self Dividing Numbers)?
This page provides optimized solutions for LeetCode problem 728 (Self Dividing Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 728 (Self Dividing Numbers)?
The time complexity for LeetCode 728 (Self Dividing Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 728 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 728 in Java, C++, or Python.