본문 바로가기
알고리즘/프로그래머스

[C++] 연속된 수의 합

by parkkingcar 2023. 5. 24.

 

연속된 수의 합

연속된 세 개의 정수를 더해 12가 되는 경우는 3, 4, 5입니다. 두 정수 num과 total이 주어집니다. 연속된 수 num개를 더한 값이 total이 될 때, 정수 배열을 오름차순으로 담아 return하도록 solution함수를 완성해보세요.

 

 

total + (total - 1) + (total - 2) + ... + (total - num) 이렇게 num개 만큼 더한 수가 처음 total 값과 같은 경우를 생각합니다. total 값을 1씩 빼면서 반복해주면 됩니다.

 

#include <string>
#include <vector>

using namespace std;

vector<int> solution(int num, int total) {
    vector<int> answer;
    int sum, total_tmp = total;
    while(1){
        sum = 0;
        for(int j = 0; j < num; j++){
            sum += total_tmp - j;
        }
        if(sum == total){
            for(int j = num; j > 0; j--){
                answer.push_back(total_tmp - j + 1);
            }
            break;
        }
        total_tmp--;
    }
    return answer;
}

'알고리즘 > 프로그래머스' 카테고리의 다른 글

[C++] 옹알이 (1)  (0) 2023.05.30
[C++] 평행  (0) 2023.05.25
[C++] 치킨 쿠폰  (0) 2023.05.23
[C++] 다음에 올 숫자  (0) 2023.05.23
[C++] 숫자 문자열과 영단어  (0) 2023.05.23

댓글