본문 바로가기
Algorithm

[프로그래머스] 나누어 떨어지는 숫자 배열 (JS, Python)

by YGSEO 2021. 1. 26.
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

댓글