예를들어 15는 다음과 같이 4가지로 표현 할 수 있습니다.
- 1 + 2 + 3 + 4 + 5 = 15
- 4 + 5 + 6 = 15
- 7 + 8 = 15
- 15 = 15
자연수 n이 매개변수로 주어질 때, 연속된 자연수들로 n을 표현하는 방법의 수를 return하는 solution를 완성해주세요.
투 포인터 이용
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int answer;
int solution(int n) {
int en = 1;
int res = 1;
for(int st=1; st<=n; st++){
while(en<=n && res<n) res += ++en;
if(res==n) answer++;
res -= st;
}
return answer;
}