面试题9 斐波那契数列

来源:互联网 发布:陆维网络图软件 编辑:程序博客网 时间:2024/05/16 15:34

地址:http://ac.jobdu.com/problem.php?pid=1387

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




输入:
输入可能包含多个测试样例,对于每个测试案例,
输入包括一个整数n(1<=n<=70)。

输出:
对应每个测试案例,
输出第n项斐波那契数列的值。

样例输入:
3
样例输出:
2

<span style="font-size:18px;">#include <stdio.h>#include <stack>using namespace std;int main(){    int n;    stack<long long> Stack;    while(scanf("%d", &n) != EOF) {        while(!Stack.empty())            Stack.pop();        if(n == 0) {            printf("0\n");            continue;        }        if(n == 1) {            printf("1\n");            continue;        }        Stack.push(0);        Stack.push(1);        long long sum = 0;        for(int i = 2; i <= n; i ++) {            sum = 0;            long long tmp = Stack.top();            Stack.pop();            sum = tmp + Stack.top();            Stack.pop();             Stack.push(tmp);            Stack.push(sum);        }        printf("%lld\n", sum);    }    return 0;}/**************************************************************    Problem: 1387    Language: C++    Result: Accepted    Time:0 ms    Memory:1052 kb****************************************************************/</span>

注意:当n较大时,斐波那契数会变得很大,超出int必须用long long存储数据


0 0
原创粉丝点击