코딩테스트/프로그래머스

프로그래머스 C++ LV1 나누어 떨어지는 숫자 배열 풀이

sky하연 2024. 4. 5. 12:39
728x90

문제 설명

array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요.
divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요.

 

코드 풀이

내가 백준에서 프로그래머스를 처음 들어오면서 겪은 문제점이 있었다.

vector<int> solution(vector<int> arr, int divisor) {

바로 이 첫번째 줄이었다.

본능적으로는 이게 메인인걸 알고 있었지만 cin이랑 cout을 쓰던 나한테는 꽤 당황스러운 일이었다.

답 출력도

    return answer;

이렇게 친절하게 해줬으니까

몇문제를 풀어보고 난 후에야 저위 vector와 int가 입력을 받는 것이란 걸 알수 있었다.

난 그냥 받아준걸 가지고 풀기만 하면 그만이었다.

 

for(int i = 0; i < arr.size(); i++){
        if(arr[i] % divisor == 0){
            answer.push_back(arr[i]);
        }
    }

arr을 divisor로 나누었을때 나누어 떨어진다면 arr을 answer뒤에 넣는다.

이건 answer[i] = arr[i]; 로 바꿔쓸 수 있을거 같다

이걸 arr의 크기만큼 반복 시켜주었다.

 

if(answer.size() <= 0){
        answer.push_back(-1);
    }

그리고 만약 answer의 크기가 0보다 작거나 같다면 answer에 -1을 추가시켜주었다.

 

sort(answer.begin(), answer.end());

마지막으로 answer를 sort함수를 활용하여 오름차순으로 배열해 주었다.

 

전체 코드

#include <string>
#include <algorithm>
#include <vector>

using namespace std;

vector<int> solution(vector<int> arr, int divisor) {
    vector<int> answer;
    for(int i = 0; i < arr.size(); i++){
        if(arr[i] % divisor == 0){
            answer.push_back(arr[i]);
        }
    }
    if(answer.size() <= 0){
        answer.push_back(-1);
    }
    sort(answer.begin(), answer.end());
    
    
    return answer;
}
728x90