Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-10870번/Java] 피보나치 수 5 본문

Algorithm

[백준-10870번/Java] 피보나치 수 5

1984 2022. 11. 18. 13:51

* 재귀 함수로 풀었다.

* N이 0일 때, 1일 때 if 문 으로 처리함.

import java.io.*;
import java.util.*;

public class Main {

	private static int fibonacci(int x, int y, int num) {
		if (num > 0) {
			return fibonacci(y, x + y, num - 1);
		}
		return x + y;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		int N = Integer.parseInt(br.readLine());

		if (N == 0) { // N이 0일 때,
			System.out.println(0);
		} else if (N == 1) { // N이 1일 때,
			System.out.println(1);
		} else { // 0, 1이 이미 주어지므로 N-2 해줘야 한다.
			System.out.println(fibonacci(0, 1, N - 2));
		}
	}
}

'Algorithm' 카테고리의 다른 글

[Array-9/Java] 격자판 최대합  (0) 2022.11.19
[String-10] 가장 짧은 문자거리  (0) 2022.11.18
[백준-10816번/Java] 숫자 카드 2  (0) 2022.11.18
[백준-2164번/Java] 카드2  (0) 2022.11.18
[백준-18870번/Java] 좌표 압축  (0) 2022.11.17
Comments