๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1789_์ˆ˜๋“ค์˜ ํ•ฉ

๋ฟŒ์•ผ._. 2023. 6. 28. 17:07

Silver V

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/1789)

< ์ˆ˜๋“ค์˜ ํ•ฉ >

 

๋ฌธ์ œ ํ’€์ด & ์ƒ๊ฐ

 

n์˜ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ๋”ํ–ˆ์„ ๋•Œ ๊ตฌํ•˜๋Š” ๊ฐ’ ๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์•„์ง€๋ฉด ์ข…๋ฃŒํ•œ๋‹ค.

๋งŒ์•ฝ 5๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด๋ฉด 1+2+3์—์„œ 1์ด ๋น ์ง€๋ฉด ๋œ๋‹ค.

 

๋ฌธ์ œ๋ฅผ ํ’€ ๋•Œ ์ฃผ์˜ํ•  ์ ์€ ์ž์—ฐ์ˆ˜ ๋ฒ”์œ„๊ฐ€ int๋ฅผ ๋ฒ—์–ด๋‚˜๋ฏ€๋กœ long์œผ๋กœ ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค.

 

 

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String args[]) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		long s = Long.parseLong(bf.readLine());
		long result = 0, cnt = 0;
		
		if(s==1) cnt=1;
		for (long i = 1; i < s; i++) {
			cnt += 1;
			result += i;
			if (result >= s) {
				break;
			}
		}
		if (result > s) {
			cnt -= 1;
		}
		System.out.println(cnt);
	}
}

 

Main

-์ž์—ฐ์ˆ˜(s) ์ž…๋ ฅ

- result : ์ˆ˜๋“ค์˜ ํ•ฉ

  cnt : ์„œ๋กœ ๋‹ค๋ฅธ N๊ฐœ์˜ ์ž์—ฐ์ˆ˜

- 1์ผ ๋•Œ๋Š” 1 ํ•˜๋‚˜๋กœ ์ž์—ฐ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ cnt=1

- 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์—ฌ ํ•ฉ์„ ๊ตฌํ–ˆ์„ ๋•Œ ์ž์—ฐ์ˆ˜๋ณด๋‹ค ๊ฐ’์ด ํฌ๊ฑฐ๋‚˜ ๊ฐ™์•„์ง€๋ฉด ์ข…๋ฃŒ

- ํ•ฉ์ด ์ž์—ฐ์ˆ˜๋ณด๋‹ค ํฌ๋‹ค๋ฉด ๋นผ์ค˜์•ผ ํ•˜๋ฏ€๋กœ cnt -1

- cnt ์ถœ๋ ฅ