题解 | #斐波那契数列#
斐波那契数列
https://www.nowcoder.com/practice/ee5d403c1172487f8c7915b3c3d924c6
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int n = in.nextInt();
System.out.println(fib2(n));
}
}
public static int fib(int n){
if(n<=2){
return 1;
}
else{
return fib(n-1) + fib(n-2);
}
}
public static int fib1(int n){
int []nums = new int[n+1];
nums[1] = 1;
nums[2] = 1;
for(int i=3;i<=n;i++){
nums[i] = nums[i -1]+nums[i-2];
}
return nums[n];
}
public static int fib2(int n){
int f1 = 1;
int f2 = 1;
int f3 = 2;
if (n<=2){
return f1;
}
for (int i = 3;i<=n;i++){
f3 = f2+f1;
f1 = f2;
f2 = f3;
}
return f3;
}
}
