LeetCode 728. Self Dividing Numbers
Description
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.
class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> ret = new ArrayList<>();
for (int n = left; n <= right; ++n) {
if (selfDividing(n)) {
ret.add(n);
}
}
return ret;
}
public boolean selfDividing(int n) {
for (char c: String.valueOf(n).toCharArray()) {
if (c == '0' || (n % (c - '0') > 0))
return false;
}
return true;
}
}
Complexity Analysis
Time Complexity: O(D), where D is the number of integers in the range [L,R], and assuming log(R) is bounded. (In general, the complexity would be O(DlogR).)
Space Complexity: O(D), the length of the answer.