Leetcode 728. Self Dividing Numbers
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.
Input: left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
left
and right
take?
1 <= left <= right <= 10000
.left
to right
), check if it is a self-dividing number.Here’s the Java code to solve the problem:
import java.util.ArrayList;
import java.util.List;
public class SelfDividingNumbers {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> result = new ArrayList<>();
for (int num = left; num <= right; num++) {
if (isSelfDividing(num)) {
result.add(num);
}
}
return result;
}
private boolean isSelfDividing(int num) {
int original = num;
while (num > 0) {
int digit = num % 10;
if (digit == 0 || original % digit != 0) {
return false;
}
num /= 10;
}
return true;
}
}
left
to right
includes n
numbers, we perform the above check for each number.Hence, the total time complexity is proportional to the number of digits processed over all numbers in the range, which can be approximated as (O(n \cdot k)), where (n) is the size of the range and (k) is the number of digits per number. If we assume (k) is upper-bounded by a small constant (since typical constraints would involve reasonably small numbers), the complexity can be simplified to (O(n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?