Self Dividing Numbers
LeetCode: Self Dividing Numbers
Problem:
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, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
- Note:
The boundaries of each input argument are 1 <= left <= right <= 10000.
- Examples:
Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
- Analysis:
For left number to right number, we do the core operation to make a number been divided by every digit which is not zero.
If the digit of a number is 0, the number is not a self-dividing number.
If the number can't be divided by it's digit, the number is not a self-dividing number.
- Code - Java:
class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> results = new ArrayList<Integer>();
for (int i = left; i <= right; i++) {
int val = i;
while (val > 0) {
int digit = val % 10;
if (digit == 0 || i % digit != 0) {
break;
}
val /= 10;
}
if (val == 0) {
results.add(i);
}
}
return results;
}
}
- Code - C++:
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> results;
for (int i = left; i <= right; i++) {
int val = i;
while (val > 0) {
int digit = val % 10;
if (digit == 0 || i % digit != 0) {
break;
}
val /= 10;
}
if (val == 0) {
results.push_back(i);
}
}
return results;
}
};
- Code - Python:
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
results = []
for i in range(left, right + 1):
val = i
while val > 0:
digit = val % 10
if digit == 0 or i % digit != 0:
break
val /= 10
if val == 0:
results.append(i)
return results
Time Complexity: O(N), N is the range from left to right
Space Complexity: O(M), M is the count of self-dividing numbers