Leetcode 728. Self Dividing Numbers
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, note that self-dividing numbers do not include any zero digits.
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
?
left
and right
are within reasonable integer limits, typically between 1 and 10000.left
is greater than right
?
left
<= right
as per the problem constraints unless specified otherwise.[left, right]
.#include <vector>
bool 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;
}
std::vector<int> selfDividingNumbers(int left, int right) {
std::vector<int> result;
for (int i = left; i <= right; ++i) {
if (isSelfDividing(i)) {
result.push_back(i);
}
}
return result;
}
d
is the number of digits in the maximum number in the range. This simplifies to O(n * log(max_num)) where n
is the number of integers in the range and log(max_num)
is the number of digits in the largest number.n
is the number of self-dividing numbers in the given range.The above implementation efficiently determines self-dividing numbers within the provided range and ensures optimal performance by using basic arithmetic operations.
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?