斐波那契数列,求第n个数

  1. 题目描述
    1. 循环实现

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39

循环实现

  • 时间辅助度 O(n)
  • 空间复杂度 O(1)
class Solution {
public:
    int Fibonacci(int n) {
        int f1 = 0;
        int f2 = 1;
        if (n == 0) return 0;
        if (n == 1) return 1;
        int fn;
        for (int i = 2; i <= n;i++){
            fn = f1 + f2;
            f1 = f2;
            f2 = fn;
        }
        return fn;
    }
};

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:斐波那契数列,求第n个数

Count:118

Author:攀登

Created At:2019-12-26, 23:12:31

Updated At:2024-06-15, 15:53:35

Url:http://jiafeimao-gjf.github.io/2019/12/26/sword-%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation