A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because128 % 1 == 0
,128 % 2 == 0
, and128 % 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.Example 1:
- Input:
- left = 1, right = 22
- Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
Note:- The boundaries of each input argument are
1 <= left <= right <= 10000
.
나의 풀이
숫자를 문자열로 만들어 쪼개서 나누어떨어지면 push로 배열에 추가하는 방법1
2
3
4
5
6
7
8// 64ms
var selfDividingNumbers = function(left, right) {
const result = [];
for (let i = left; i <= right; i++) {
if(i.toString().split('').every(item => i % parseInt(item) === 0)) result.push(i);
}
return result
};
그런데 0이 포함되면 self-dividing number가 아니므로 이렇게 추가해줘도 될 것 같다.1
2
3
4
5
6
7
8/// 68ms
var selfDividingNumbers = function(left, right) {
const result = [];
for (let i = left; i <= right; i++) {
if(i % 10 !== 0 && i.toString().split('').every(item => i % parseInt(item) === 0)) result.push(i);
}
return result
};
1 | var selfDividingNumbers = function(left, right) { |