min's devlog

[Two pointers] 연속된 자연수의 합 본문

til/Algorithm

[Two pointers] 연속된 자연수의 합

값진 2021. 7. 30. 19:40
import java.util.*;
class Main {	
	public int solution(int n){
		int answer=0, sum=0;
		int m=n/2+1;
		int[] arr=new int[m];
		for(int i=0; i<m; i++) arr[i]=i+1; //0번인덱스에1
		int lt=0;
		for(int rt=0; rt<m; rt++){
			sum+=arr[rt];
			if(sum==n) answer++; //n주의
			while(sum>=n){
				sum-=arr[lt++];
				if(sum==n) answer++; 
			}
		}
		return answer;
	}

	public static void main(String[] args){
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		int n=kb.nextInt();
		System.out.print(T.solution(n));
	}
}

'til > Algorithm' 카테고리의 다른 글

5x5 마방진  (0) 2022.04.07
회장 선거  (0) 2021.07.31
연속부분수열  (0) 2021.07.30
[Sliding window] 최대 매출  (0) 2021.07.28
[Two pointers] 공통원소 구하기  (0) 2021.07.28
Comments