首页 > 其他 > 详细

剑指offer7-斐波那契数列

时间:2020-05-11 14:40:37      阅读:43      评论:0      收藏:0      [点我收藏+]

题目描述

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

n<=39

思路:该题有两种方法。

一种是递归的

一种是非递归的,

 

代码:

class Solution {
public:
    int Fibonacci(int n) {
        if(n==0) return 0;
        if(n==1) return 1;
        int num_first=0;
        int num_second=1;
        int temp;
        if(n>=2)
        {
            for(int i=2;i<=n;i++)
            {
                temp = num_first + num_second;
                num_first = num_second;
                num_second = temp;
                
            }
        }
        return temp;
        
        /*
        //没有弄懂自己哪里错了
        if(n>=2)
        {
            for(int i=2;i<n;i++)
            {
                a[i]=a[i-1]+a[i-2];
            }
        }
        */
        
       
    }
};

 

剑指offer7-斐波那契数列

原文:https://www.cnblogs.com/loyolh/p/12868776.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!