劍指offer第7題:
大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項爲0)。(n<=39)
理解:
本題沒有太大的難度,需要瞭解斐波那契數列的計算規則。按照規則第0項爲0,第一項和第二項爲1,後面按照規則相加計算即可。注意處理好for循環的循環邊界。
public class Solution {
public int Fibonacci(int n) {
//創建前兩項和result
int one = 0;
int two = 1;
int result = 0;
if(n == 0){ //前兩項特殊處理
return one;
}
else if(n == 1){
return two;
}
else{
for(int i = 2; i <= n; i++){ //後面用斐波那契規則計算即可
result = one + two;
one = two;
two = result;
}
}
return result;
}
}
知識點:
- 斐波那契數列
- for循環