您的位置:首页 > 其它

366. 斐波纳契数列

2017-12-08 10:52 155 查看
描述:

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

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

前2个数是 0 和 1 。

第 i 个数是第 i-1 个数和第i-2 个数的和。

斐波纳契数列的前10个数字是:

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


注意事项:

The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

(翻译:在给出的测试案例中,第N个斐波那契数不会超出32位signed integer的最大取值范围)

样例

给定
1
,返回
0


给定
2
,返回
1


给定
10
,返回
34


思路:

初始值第一个斐波那契数是0,第二个是1,然后根据第一和第二个递推出后面的第N个。

Java代码:

1 public int fibonacci(int n)
2 {
3     if (n <= 0) return -1;
4     if (n == 1) return 0;
5     if (n == 2) return 1;
6
7     int n1 = 0;
8     int n2 = 1;
9     int target = 0;
10
11     for(int i = 3; i <= n; i++)
12     {
13         target = n1 + n2;
14         n1 = n2;
15         n2 = target;
16     }
17
18     return target;
19 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: