题目:
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.
The boundaries of each input argument are 1 <= left <= right <= 10000
.
思路:
时间复杂度为O(nm), n = right - left,m 是迭代的数中的位数。
class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> list = new ArrayList<>();
for (int num = left; num <= right; num++)
{
int temp = num;
for (; temp > 0; temp /= 10)
if ((temp % 10 == 0) || (num % (temp % 10)) != 0)
break;
if (temp == 0)
list.add(num);
}
return list;
}
}
class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
List<Integer> list = new LinkedList<>();
for (int num = left; num <= right; num++)
{
if (helper(num)) list.add(num);
}
return list;
}
private boolean helper(int a)
{
int b = a;
while (b > 0)
{
if (b % 10 == 0) return false;
if (a % (b % 10) != 0) return false;
b = b / 10;
}
return true;
}
}