Coding Problem/프로그래머스

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

마탁이 2021. 4. 29. 21:38

programmers.co.kr/learn/courses/30/lessons/12910

 

코딩테스트 연습 - 나누어 떨어지는 숫자 배열

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

programmers.co.kr

더보기
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

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

    vector<int>::const_iterator iter = arr.begin();
    while (iter != arr.end())
    {
        if (0 == *iter % divisor)
            answer.push_back(*iter);
        ++iter;
    }

    if (true == answer.empty())
        answer.push_back(-1);
    else
        sort(answer.begin(), answer.end());

    return answer;
}


int main()
{
    vector<int> arr = { 3,2,6 };
    int divisor = 10;
    vector<int> answer = solution(arr, divisor);
    for (auto ans : answer)
    {
        printf("%d ", ans);
    }
    
    return 0;
}