본문 바로가기
프로그래머스코딩테스트연습풀이/C++

[프로그래머스/C++] 홀수 vs 짝수

by 코코쵸마 2025. 2. 15.

문제

정수 리스트 num_list가 주어집니다. 가장 첫 번째 원소를 1번 원소라고 할 때, 홀수 번째 원소들의 합과 짝수 번째 원소들의 합 중 큰 값을 return 하도록 solution 함수를 완성해주세요. 두 값이 같을 경우 그 값을 return합니다.

 

솔루션

#include <string>
#include <vector>

using namespace std;

int solution(vector<int> num_list) {
    int even = 0;
    int odd = 0;
    for(int i = 0; i < num_list.size(); i++){
        if((i+1)%2==0){
            even += num_list[i];
        }
        else{
            odd += num_list[i];
        }
    }
    if(even > odd){
        return even;
    }
    else{
        return odd;
    }
}

 

https://school.programmers.co.kr/learn/courses/30/lessons/181887

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr