본문 바로가기

코딩테스트 스터디

코딩테스트 연습 - 약수 구하기 (JAVA)

프로그래머스 코딩테스트 입문 0단계 문제입니다

https://school.programmers.co.kr/learn/courses/30/lessons/120897 

 

📢 문제 설명

정수 n이 매개변수로 주어질 때, n의 약수를 오름차순으로 담은 배열을 return하도록 solution 함수를 완성해주세요.

 

⭕ 정답 코드

1. Stream 사용

import java.util.stream.IntStream;
class Solution {
    public int[] solution(int n) {
        return IntStream.rangeClosed(1, n).filter(i -> n%i==0).toArray();
    }
}

 

🔍 해설

1부터 n까지의 숫자를 갖는 IntStream을 만들고

filter()로 n으로 나누면 나머지가 0인 요소들만 남긴다

toArray()을 사용하여 배열로 변환해준다

 

 

import java.util.*;
class Solution {
    public int[] solution(int n) {
        List<Integer> list = new ArrayList<>();
        
        for(int i = 1; i<=n; i++)
            if(n%i==0) list.add(i);
        
        return list.stream().mapToInt(i->i).toArray();
    }
}

🔍 해설

Integer List를 만들어주고

for문으로 조건에 맞는 숫자만 List에 추가해준다

배열로 바꾸어준다

(Stream에 관한 설명은 글의 맨 밑을 참고해주세요)

 

 

⚠️ 직접 풀어본 처음 풀이

🔗 코드

1. Stream 사용

import java.util.stream.IntStream;
class Solution {
    public int[] solution(int n) {
        IntStream stream = IntStream.rangeClosed(1, n);
        return stream.filter(i -> n%i==0).toArray();
    }
}

🔍 해설

1부터 n까지의 숫자를 갖는 IntStream을 만들고

filter()로 n으로 나누면 나머지가 0인 요소들만 남긴다

toArray()을 사용하여 배열로 변환해준다

 

2. for문과 배열 사용

class Solution {
    public int[] solution(int n) {
        
        int cnt = 0;
        for(int i = 1; i<n+1; i++)
            if(n%i==0) cnt++;
        
        int[] answer = new int[cnt];
        
        int index = 0;
        for(int i = 1; i<n+1; i++)
            if(n%i==0) answer[index++] = i;
        
        return answer;
    }
}

🔍 해설

answer 배열의 길이가 될 cnt 변수를 0으로 초기화한다

for문 안에서 조건에 해당하는 숫자가 있을때마다 1씩 더하여준다

 

구해진 배열의 길이로 answer 배열을 선언해준다

answer의 인덱스로 쓰일 index 변수를 0으로 초기화한다

 

조건에 해당하는 숫자가 있을때마다 answer의 index방에 그 숫자를 넣고

index는 1씩 증가시켜준다

 

📒 기억하고 갈 문법

Stream을
int로 바꾸어주는 mapToInt()
배열로 바꾸어주는 toArray()

 

Stream의 map()은 stream의 내용을 수정하여 적용시켜주는 메서드이다

mapToInt()는 map()과 같은 기능을 하지만

int로 반환을 해주는 부분에서 차이점이 있다

 

그래서 mapToInt(i -> i)를 해주면

stream의 요소들을 int로 바꾸어줄 수 있다

 

이후 Stream을 배열로 반환해주는

toArray() 메서드를 사용해서 정답으로 제출해준다

 

* 참고 블로그: https://velog.io/@sa833591/Java-Stream-3#8-maptoint-maptolong-maptodouble