Sponsored
Sponsored
This approach involves iterating over each number within the given range. For each number, extract each digit and check if the number is evenly divisible by that digit. If it passes all checks, the number is self-dividing.
Time Complexity: O(n*m), where n is the range and m is the number of digits in each number.
Space Complexity: O(1) since no extra space is used proportional to input size.
1import java.util.ArrayList;
2import java.util.List;
3
4public class SelfDividingNumbers {
5
6 public static boolean isSelfDividing(int num) {
7 int original = num, digit;
8 while (num > 0) {
9 digit = num % 10;
10 if (digit == 0 || original % digit != 0) {
11 return false;
12 }
13 num /= 10;
14 }
15 return true;
16 }
17
18 public static List<Integer> selfDividingNumbers(int left, int right) {
19 List<Integer> result = new ArrayList<>();
20 for (int i = left; i <= right; i++) {
21 if (isSelfDividing(i)) {
22 result.add(i);
23 }
24 }
25 return result;
26 }
27
28 public static void main(String[] args) {
29 int left = 1, right = 22;
30 List<Integer> result = selfDividingNumbers(left, right);
31 System.out.println(result);
32 }
33}
In this Java solution, we use an ArrayList
to keep track of all self-dividing numbers. The function checks each number from left
to right
to determine if it satisfies the self-dividing condition.
This approach optimizes the check by making a presumption against numbers containing digit zero immediately. Numbers with digit zero are automatically non-self-divisible. For the rest, we still check each digit, but this could reduce the number of required operations.
Time Complexity: O(n*m), where n is the range and m is reduced due to skipping numbers.
Space Complexity: O(1).
1
In the Java version, the selfDividingNumbers
method reduces calls to isSelfDividing
by prescreening numbers divisible by ten. This minimization helps to avoid futile checks.