【算法编程】斐波那契数列

题目来源:牛客网剑指offer

题目描述:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39

C++:5ms 476k

#include <iostream>
using namespace std;

class Solution {
public:
    int Fibonacci(int n) {
        int temp = 1;
        int function = 0;
        while(n--){
            function += temp;
            temp = function - temp;
        }
        return function;
    }
};

int main()
{
    Solution obj;
    int n;
    while(cin>>n){
        cout<<obj.Fibonacci(n)<<endl;
    }
    cin.get();
    cin.get();
}

Python:33ms 5724k

# -*- coding:utf-8 -*-
import sys
class Solution:
    def Fibonacci(self, n):
        function = 0
        temp = 1
        while(n):
            function += temp
            temp = function - temp
            n -= 1
        return function

if __name__ == '__main__':
    obj = Solution()
    while (1):
        x = input()
        print obj.Fibonacci(x)

猜你喜欢

转载自www.cnblogs.com/xiangfeidemengzhu/p/9149244.html