查找斐波納契數列中第 N 個數。
所謂的斐波納契數列是指:
- 前2個數是 0 和 1 。
- 第 i 個數是第 i-1 個數和第i-2 個數的和。
斐波納契數列的前10個數字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
樣例
樣例 1:
輸入: 1
輸出: 0
樣例解釋:
返回斐波那契的第一個數字,是0.
樣例 2:
輸入: 2
輸出: 1
樣例解釋:
返回斐波那契的第二個數字是1.
注意事項
在測試數據中第 N 個斐波那契數不會超過32位帶符號整數的表示範圍
public class Solution {
/**
* @param n: an integer
* @return: an ineger f(n)
*非遞歸算法
*/
public int fibonacci(int n) {
int sum = 0;
// write your code here
if(n == 1){
return 0;
}
else if(n == 2||n == 3){
return 1;
}
else{
int s2 = 1;
int s3 = 1;
int i = 4;//0, 1, 1, 2~從第四項開始計算
while(i<=n){
sum = s2+s3;
s2 = s3;
s3 = sum;
i++;
}
return sum;
}
}
}