1.标题:Fibonacci数列
public class Test13 {
private static int Solution(int num){
int a = 0;
int index = 0;
int result = 0;
for(int i = 1;Fab(i)<num;i++){
a = Fab(i);
index++;
}
int b = Fab(index+1);
if(num==b){
return 0;
}else {
result = Math.min(num-a,b-num);
}
return result;
}
private static int Fab(int num){
if(num==1||num==2){
return 1;
}
return Fab(num-1)+Fab(num-2);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int result = Solution(num);
System.out.println(result);
}
}
//方法二:
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int n = 0;
int a = 0, b = 1, c = 1;
if (scanner.hasNextInt()) {
n = scanner.nextInt();
}
while (c < n) {
a = b;
b = c;
c = a + b;
}
int dis1 = n - b;
int dis2 = c - n;
System.out.println(dis1 < dis2 ? dis1 : dis2);
}
}
2.标题:机器人走方格I
有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。请设计一个算法,计算机器人有多少种走法。
给定两个正整数int x,int y,请返回机器人的走法数目。保证x+y小于等于12。
测试样例:
2,2
返回:2
//方格子问题
public class Robot {
public int countWays(int x, int y) {
if (x == 1 || y == 1) return 1;
return countWays(x - 1, y) + countWays(x, y - 1);
}
}