땀두 블로그

[백준] 2747번 - 피보나치 수 본문

알고리즘/백준

[백준] 2747번 - 피보나치 수

땀두 2022. 3. 20. 12:18

 

 

피보나치 수열을 구하는 가장 기본문제이다. 처음에 재귀로 풀었다가 시간초과가 나서 조건문을 이용하여 풀어 해결하였다.

 

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

public class p2747 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int a = 0;
		int b = 1;
		int sum = 0;
		int n = Integer.parseInt(br.readLine());
		if (n == 0) {
			System.out.println(0);
		} else if (n == 1) {
			System.out.println(1);
		} else {
			for (int i = 1; i < n; i++) {
				sum = a + b;
				a = b;
				b = sum;
			}
			System.out.println(sum);
		}
	}
}
 

 

 

Comments