최대 1 분 소요

Question

Q


Solution

  • for루프로 1~n 까지 연속되는 숫자를 더해가며 조건이 만족하는 것의 개수를 찾는다.
  • 연속되는 숫자의 합은 재귀를 활용하여 구현하였다.

Cord

#include <string>
#include <vector>

using namespace std;


bool sum(int limit, int a, int& total)
{
    total += a;
    
    if (total > limit) { return false; }
    else if (total == limit) { return true; }
    
    return sum(limit, a + 1, total);
}

int solution(int n) 
{
    int answer = 0;
    
    // 1~n 범위에서 가능한 것 찾아 카운팅 
    for(int i = 1; i <= n; i++)
    {
        int total = 0;
        if (sum(n, i, total)) { answer++; }
    }
    
    return answer;
}

Result

Result