[C++] 프로그래머스 이어 붙인 수

문제설명

정수가 담긴 리스트 num_list가 주어집니다.
num_list의 홀수만 순서대로 이어 붙인 수와
짝수만 순서대로 이어 붙인 수의 합을 return하도록
solution 함수를 완성해주세요.


제한사항

• 2 ≤ num_list의 길이 ≤ 10
• 1 ≤ num_list의 원소 ≤ 9
• num_list에는 적어도 한 개씩의 짝수와 홀수가 있습니다.


입출력 예

num_list result
[3, 4, 5, 2, 1] 393
[5, 7, 8, 3] 581


풀이

even과 odd문자열에 num_list의 홀수와 짝수를 이어 붙여 숫자로 변환한 뒤 계산하는 로직을 구현했습니다.

#include <string>
#include <vector>

using namespace std;

int solution(vector<int> num_list) {
    int answer = 0;
    
    string even = "";
    string odd = "";
    
    int even_num = 0;
    int odd_num = 0;
    
    for(int i = 0; i < num_list.size(); i++)
    {
        if(num_list[i] % 2 == 0)
        {
            even += to_string(num_list[i]);
        }
        else
        {
            odd += to_string(num_list[i]);
        }
    }
    
    even_num = even == "" ? 0 : stoi(even);
    odd_num = odd == "" ? 0 : stoi(odd);
    
    answer = even_num + odd_num;
    
    return answer;
}


결과

코드 실행결과

Categories:

Updated:

Leave a comment