剑指 Offer-JZ7-斐波那契数列

题目描述

大家都知道斐波那契数列,现在要求输入一个整数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 first = 0;
        int second = 1;
        int index = 1;
        while(true){
            int third = first + second;
            index ++;
            if(index == n){
                return third;
            }
            else{
                first = second;
                second = third;
            }
        }
    }
};

结果

运行时间:3ms
占用内存:480k

你可能感兴趣的:(剑指offer)