1. 问题
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.
例子
Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
2. 我的解法
var selfDividingNumbers = function(left, right) {
let output = []
while (left <= right) {
const tempList = left.toString().split('')
if(tempList.every( v => left % v === 0) && !tempList.includes('0')) {
output = [...output, left]
}
left ++
}
return output
};
Runtime: 68 ms, faster than 69.27% of JavaScript online submissions for Self Dividing Numbers.
Memory Usage: 37.8 MB, less than 35.48% of JavaScript online submissions for Self Dividing Numbers
3. 其他解法
var selfDividingNumbers = function(left, right) {
let r,d;
const nums = [];
for (let num=left; num<=right; num+=1) {
d=num;
r=num%10;
while (r && !(num%r)) {
d=Math.floor(d/10);
r=d%10;
}
if (d===0) nums.push(num);
}
return nums;
};
这个要领不必转化成字符串,直接获得的数再除