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).
1using System.Collections.Generic;
class SelfDividingNumbers
{
public static bool IsSelfDividing(int num)
{
int original = num, digit;
while (num > 0)
{
digit = num % 10;
if (digit == 0 || original % digit != 0)
{
return false;
}
num /= 10;
}
return true;
}
public static List<int> SelfDividingNumbersInRange(int left, int right)
{
List<int> result = new List<int>();
for (int i = left; i <= right; i++)
{
if ((i % 10 != 0) && IsSelfDividing(i))
{
result.Add(i);
}
}
return result;
}
static void Main()
{
int left = 47, right = 85;
List<int> result = SelfDividingNumbersInRange(left, right);
Console.WriteLine(string.Join(", ", result));
}
}
Similar to previous examples, the C# solution looks for numbers not ending in zero, thus reducing false eliminations of qualifying candidates through smart filtering before detailed evaluation.