Posts [프로그래머스] 나누어 떨어지는 숫자 배열 / C++
Post
Cancel

[프로그래머스] 나누어 떨어지는 숫자 배열 / C++


Contents



문제


문제를 보시려면 링크를 클릭해주세요.


풀이


  1. arr 요소가 divisor로 나누어 떨어질 때, 해당 값을 answer 벡터에 담아줍니다.

  2. answer 벡터를 오름차순 정렬합니다.

  3. answer 벡터가 비어있을땐 나누어 떨어지는 요소가 없는 경우이므로 -1을 담아줍니다.


소스 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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]);
    }
    
    sort(answer.begin(), answer.end());
    
    if(answer.empty())
        answer.push_back(-1);
    
    return answer;
}



This post is licensed under CC BY 4.0 by the author.

[프로그래머스] 문자열 다루기 기본 / C++

[프로그래머스] 문자열 내 마음대로 정렬하기 / C++

Comments powered by Disqus.