【Lintcode】斐波纳契数列

来源:互联网 发布:python ggplot 保存 编辑:程序博客网 时间:2024/06/05 20:49

描述

查找斐波纳契数列中第 N 个数。

所谓的斐波纳契数列是指:

  • 前2个数是 0 和 1 。
  • 第 i 个数是第 i-1 个数和第i-2 个数的和。
    斐波纳契数列的前10个数字是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 …

样例

给定 1,返回 0
给定 2,返回 1
给定 10,返回 34

java code(非递归)

class Solution {/** * @param n: an integer * @return an integer f(n) */public int fibonacci(int n) {    // write your code here    if (n==1)         return 0;     if (n == 2)         return 1;    int f0 = 0;    int f1 = 1;    int i = 3;    int f = 0;    while(i <= n) {        f = f0 + f1;        f0 = f1;        f1 = f;        i++;    }    return f;    }}
0 0
原创粉丝点击