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.
1#include <iostream>
2#include <vector>
3
4bool isSelfDividing(int num) {
5 int original = num, digit;
6 while (num > 0) {
7 digit = num % 10;
8 if (digit == 0 || original % digit != 0) {
9 return false;
10 }
11 num /= 10;
12 }
13 return true;
14}
15
16std::vector<int> selfDividingNumbers(int left, int right) {
17 std::vector<int> result;
18 for (int i = left; i <= right; i++) {
19 if (isSelfDividing(i)) {
20 result.push_back(i);
21 }
22 }
23 return result;
24}
25
26int main() {
27 int left = 1, right = 22;
28 std::vector<int> result = selfDividingNumbers(left, right);
29 for (int number : result) {
30 std::cout << number << " ";
31 }
32 return 0;
33}
The C++ solution uses a vector to store self-dividing numbers found within the range. The isSelfDividing
function evaluates whether each number is self-dividing by checking modulus conditions for all digits.
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.