Super Kawaii Cute Cat Kaoani [JAVA][Baekjoon] 2018번 수들의 합 5

[JAVA][Baekjoon] 2018번 수들의 합 5

2024. 3. 23. 15:06
728x90
SMALL
 

2018번: 수들의 합 5

어떠한 자연수 N은, 몇 개의 연속된 자연수의 합으로 나타낼 수 있다. 당신은 어떤 자연수 N(1 ≤ N ≤ 10,000,000)에 대해서, 이 N을 몇 개의 연속된 자연수의 합으로 나타내는 가지수를 알고 싶어한

www.acmicpc.net


 

 

📌 투포인터 사용

  • start_index와 end_index를 한 칸씩 이동해가면서 구하는 방법!
  • sum > N
    • sum = sum - start_index; 
    • start_index ++;
  • sum < N
    • end_index++;
    • sum = sum + end_index
  • sum = N 
    • cnt ++ ;
    • end_index++; 

 

✅ PASS CODE

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {
   public static void main(String [] args) throws IOException {

       Scanner sc = new Scanner(System.in);
       int N = sc.nextInt();

       /**
        * N (자기 자신)을 선택할 경우가 있기 때문에 1로 초기화
        */
       int cnt = 1; // 자기 자신(N)
       int sum = 1;
       int start_index = 1, end_index = 1;
       
       while(end_index != N){
           if(sum == N){
               cnt ++;     
               end_index++;
               sum += end_index;
           }
           else if(sum<N){
               end_index++;
               sum += end_index;
           }
           else {
               sum -= start_index;
               start_index++;
           }
       }
       System.out.println(cnt);


   }
}

 

728x90
LIST

BELATED ARTICLES

more