Write a function and enter n to find the nth term of the Fibonacci sequence. The definition of Fibonacci sequence is as follows:
F(0) = 0, F(1) = 1
F(N) = F(N-1) + F(N-2), where N> 1. The
Fibonacci sequence starts with 0 and 1, and the following The Fibonacci number is obtained by adding the previous two numbers.
The answer needs to be modulo 1e9+7 (1000000007). If the initial result of the calculation is: 1000000008, please return 1.
Example 1:
Input: n = 2
Output: 1
Example 2:
Input: n = 5
Output: 5
Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
The idea of this question is relatively simple, the main thing is to pay attention to it, that is, take the surplus, and teach with blood and tears!
Code! ! !
/**
* @param {number} n
* @return {number}
*/
var fib = function(n) {
if(n==0)return 0;
if(n==1) return 1;
let s=0;
let l=1;
for(let i=1;i<n;i++)
{
let t = s
s = l
l = (t + l)%1000000007;
}
return l;
};