백준 - 10870 피보나치 수 5
문제
10870 피보나치 수 5
답
1. kotlin code: 재귀
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fun main() {
q10870()
}
fun q10870() {
val n = readln().toInt()
println(fibonacci(n))
}
fun fibonacci(n: Int): Int = when(n) {
0, 1 -> n
else -> fibonacci(n - 1) + fibonacci(n - 2)
}
2. kotlin code: 꼬리 재귀
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fun main() {
q10870()
}
fun q10870() {
val n = readln().toInt()
println(fibonacciWithTailRec(n))
}
tailrec fun fibonacciWithTailRec(n: Int, a: Int = 0, b: Int = 1): Int = when(n) {
0 -> a
1 -> b
else -> fibonacciWithTailRec(n - 1, b, a + b)
}
This post is licensed under CC BY 4.0 by the author.