[Greedy] 1789번 - 수들의 합

안수진·2024년 5월 18일

Baekjoon

목록 보기
22/55
post-thumbnail

[백준] 1789번 - 수들의 합

📝 나의 풀이

위 사진처럼 1부터 차례대로 더한 값이 S보다 커진 경우 반복문을 종료한다.
수를 더한 횟수에서 1을 뺀, 즉 count -1 한 값이 정답이 된다.

👩🏻‍💻 최종 코드

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long S = sc.nextLong();
		
		long sum = 0;
		int count = 0;

		while(true) {
			count++;
			sum += count;
			
			if(sum > S) break;
		}
		
		System.out.println(count - 1);

	}

}
profile
항상 궁금해하기

0개의 댓글