[프로그래머스] Level1. 나누어 떨어지는 숫자 배열

Benjamin·2023년 3월 11일
0

프로그래머스

목록 보기
40/58

내 풀이

import java.util.Arrays;

class Solution {
    public int[] solution(int[] arr, int divisor) {
        String answerString ="";
        for(int i=0; i<arr.length; i++) {
            if(arr[i] %divisor ==0) answerString += arr[i] + ",";
        }
        if(answerString.equals("")) {
            int[] answer = new int[1];
            answer[0] = -1;
            return answer;
        }
        String[] temp = answerString.split(",");
        int[] answer = new int[temp.length];
        for(int i=0; i<temp.length; i++) {
            answer[i] = Integer.parseInt(temp[i]);
        }
        Arrays.sort(answer);
        return answer;
    }
}

코드가 조금 지저분한것같다..

다른 풀이

import java.util.Arrays;

class Solution {
    public int[] solution(int[] arr, int divisor) {
        int[] answer = Arrays.stream(arr).filter(factor -> factor % divisor == 0).toArray();
        Arrays.sort(answer);
        if(answer.length ==0) {
            answer = new int[1];
            answer[0] = -1;
        }
        return answer;
    }
}

공부한 사항

  1. 우선 이렇게 int[] answer = Arrays.stream(arr).filter(factor -> factor % divisor == 0).toArray(); stream을 이용하고 다시 배열로 바꾸는 식을 잘 공부해둬야겠다.

  2. 또한

if(answer.length ==0) {
    answer = new int[1];
    answer[0] = -1;
}

이렇게 크기 초기화 해준 후, 값 대입하는 식 대신 처음부터 값으로 초기화하는것도 잊지말아야겠다.

if(answer.length == 0) answer = new int[] {-1};

이미 answer이 초기화되어있기도하고, if(answer.length ==0) int[] answers = {-1};이렇게 if문에서 배열을 선언하면 error: variable declaration not allowed here에러가 난다.

배열 변수를 미리 선언한 후 값 목록들이 나중에 결정되는 상황에는 new 연산자를 사용해 값의 목록을 지정해주면된다. new 뒤에는 "타입[]"을 붙이고 중괄호{}에는 값들을 나열한다.
변수 = new 타입[] {값0, 값1, ...};

0개의 댓글