문제
array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요.
divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요.제한사항
- arr은 자연수를 담은 배열입니다.
- 정수 i, j에 대해 i ≠ j 이면 arr[i] ≠ arr[j] 입니다.
- divisor는 자연수입니다.
- array는 길이 1 이상인 배열입니다.
코드
#include <string>
#include <vector>
#include <algorithm>
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.empty())
answer.push_back(-1);
sort(answer.begin(), answer.end());
return answer;
}
나의 생각
'Algorithm > 프로그래머스 : Level 1' 카테고리의 다른 글
[프로그래머스 Level 1] 정수 내림차순으로 배치하기 (0) | 2021.11.16 |
---|---|
[프로그래머스 Level 1] 자연수 뒤집어 배열로 만들기 (0) | 2021.11.15 |
[프로그래머스 Level 1] 두 정수 사이의 합 (0) | 2021.11.14 |
[프로그래머스 Level 1] 자릿수 더하기 (0) | 2021.11.14 |
[프로그래머스 Level 1] 같은 숫자는 싫어 (0) | 2021.11.13 |