剑指OfferJZ7 斐波那契数列(JavaScript:循环)

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M 热度指数:982517
本题知识点: 数组

题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。
n\leq 39n≤39

示例1
输入
4
返回值
3

对斐波那契数列不了解的参考:JavaScript实现斐波那契数列
思路就是斐波那契

function Fibonacci(n)
{
    
    
    // write code here
    if(n === 0) return 0
    else if (n === 1) return 1
    else if (n === 2) return 1
    let left = 0 , right = 1 ,res = 0
    for(let i = 2 ; i <= n ; i++){
    
    
        res = left + right
        left = right
        right = res
    }
    return res
}

猜你喜欢

转载自blog.csdn.net/weixin_44523860/article/details/113558116