GitHubSeob
C++ / 프로그래머스 / 나누어 떨어지는 숫자 배열 본문
문제
https://programmers.co.kr/learn/courses/30/lessons/12910
코딩테스트 연습 - 나누어 떨어지는 숫자 배열
array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요. divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하
programmers.co.kr
문제풀이
배열의 값을 divistor로 나눈 나머지가 0이면 answer에 push 하면 된다.
입출력 예에서 return부분을 보면 항상 정렬이 되어있으므로 처음에 arr배열을 정렬해야 한다.
answer을 return 하기 전에 비어있을 경우 -1을 push 한다.
코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> arr, int divisor) {
vector<int> answer;
sort(arr.begin(), arr.end());
for (int idx = 0; idx < arr.size(); ++idx)
if (arr[idx] % divisor == 0)
answer.push_back(arr[idx]);
if (answer.empty()) answer.push_back(-1);
return answer;
}
'Programmers > Level 1' 카테고리의 다른 글
C++ / 프로그래머스 / [1차] 다트 게임 (0) | 2021.09.06 |
---|---|
C++ / 프로그래머스 / [1차] 비밀지도 (0) | 2021.08.30 |
C++ / 프로그래머스 / 같은 숫자는 싫어 (0) | 2021.08.28 |
C++ / 프로그래머스 / 가운데 글자 가져오기 (0) | 2021.08.28 |
C++ / 프로그래머스 / 2016년 (0) | 2021.08.28 |