遇到一个Java算法题,题目是,第一个数是1,第二个数是1,从第三个数开始当前数是前两个数之和,如(1,1,2,3,5,8,13……)
这个用到了递归。代码如下:
public class Test {
private static int a;
public static int getValue(int index) {
if (index == 1) {
a = 1;
}
if (index == 2) {
a = 1;
}
if (index >= 3) {
a = getValue(index - 1) + getValue(index - 2);
}
return a;
}
public static void main(String[] args) {
System.out.print(getValue(10));
}
}
运行后结果是对的。