Generate Fibonacci Number
2022年5月1日小于 1 分钟
Generate Fibonacci Number
Question
0
1
1 = 0 + 1
2 = 1 + 1
3 = 1 + 2
5 = 2 + 3
8 = 3 + 5
13 = 5 + 8
....
[0,1,1,2,3,5,8,13 ...]
Given 2 initial numbers, we can generate a sequence by adding the sum of last two numbers as a new lement.
This is Fibonacci number.
You are asked to create a fib(n)
function, which generate the n-th Fibonacci number.
What is the time & space cost of your solution?
Code
/**
* @param {number} n - non-negative integer
* @return {number}
*/
function fib(n) {
// your code here
}