728x90
JS
function solution(arr, divisor) {
let tmp = [];
for (let i=0; i<arr.length; i++) {
if (arr[i] % divisor === 0) {
tmp.push(arr[i])
} else {
continue
};
};
if (tmp.length === 0) {
return [-1]
} else {
return tmp.sort((a,b) => a-b)
}
}
Next time I have to try filter method and ? operator.
function solution(arr, divisor) {
var answer = arr.filter(v => v%divisor == 0);
return answer.length == 0 ? [-1] : answer.sort((a,b) => a-b);
}
Python
def solution(arr, divisor):
answer = []
for i in range(len(arr)):
if arr[i] % divisor == 0:
answer.append(arr[i])
else:
continue
if len(answer) == 0:
return [-1]
else:
return sorted(answer)
other solution:
using list comprehension, make a loop consice.
def solution(arr, divisor):
arr = [x for x in arr if x % divisor == 0];
arr.sort();
return arr if len(arr) != 0 else [-1];
728x90
'Algorithm' 카테고리의 다른 글
[프로그래머스] 문자열 내 마음대로 정렬하기 (Python , JS) (0) | 2021.01.28 |
---|---|
[프로그래머스] 두 정수 사이의 합 (JS, Python) (0) | 2021.01.26 |
[프로그래머스] 같은 숫자는 싫어 (python, js) (0) | 2021.01.26 |
[프로그래머스] 3진법 뒤집기 (JS, Python) (0) | 2021.01.26 |
[프로그래머스] 가운데 글자 가져오기 (JS, Python) (0) | 2021.01.25 |
댓글