斐波那契數列 java
阿新 • • 發佈:2018-11-08
斐波那契數列 java
題目描述
大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項為0)。其中:n<=39
程式碼1:
public class Solution { public int Fibonacci(int n) { int a = 0, b = 1; int c = 0; for(int i = 0; i <= n; i++){ if(i == 0){ c = a; }else if(i == 1){ c = b; }else if(i > 1){ c = a + b; a = b; b = c; } } return c; } }
程式碼2:推薦
public class Solution { public int Fibonacci(int n) { int a = 0, b = 1; int c = 0; for(int i = 0; i <= n; i++){ if(i == 1){ c = b; }else if(i > 1){ c = a + b; a = b; b = c; } } return c; } }
程式碼3:採用遞迴方式
public class Solution {
public int Fibonacci(int n) {
int c = 0;
if(n == 0){
c = 0;
}else if(n == 1){
c = 1;
}else{
c = Fibonacci(n - 1) + Fibonacci(n - 2);
}
return c;
}
}