面试题10_2:跳台阶
这个题目需要注意,其实就是斐波那契数列。
Java版本
package zr.test;
/**
* @author ZR
* @Classname Num_10_2
* @Description 青蛙跳台阶
* @Date 2020/7/16 17:00
*/
public class Num_10_2 {
public static void main(String[] argv) {
}
public static int JumpFloor(int target) {
if (target == 1)
return 1;
if (target == 2)
return 2;
int fibNMinusOne = 1;
int fibNMinusTwo = 2;
int fibN = 0;
for(int i = 3; i <= target; i++){
fibN = fibNMinusOne + fibNMinusTwo;
fibNMinusOne = fibNMinusTwo;
fibNMinusTwo = fibN;
}
return fibN;
}
}
C++版本
#include <iostream>
using namespace std;
int Fibonacci(int target){
int result[2] = {1,2};
if(target <= 2)
return result[target-1];
int fibNMinusOne = 1;
int fibNMinusTwo = 2;
int fibN = 0;
for(int i = 3; i <= target; i++){
fibN = fibNMinusOne + fibNMinusTwo;
fibNMinusOne = fibNMinusTwo;
fibNMinusTwo = fibN;
}
return fibN;
}
int main(){
int a[5] = {1,2,3,4,5};
cout<<&a[2]<<" "<<&a[3]<<endl;
cout<<Fibonacci(6)<<endl;
return 0;
}