目录
1. 递归求N的阶乘
2. 按顺序打印一个数字的每一位
3. 递归求n的和
4. 计算一个数每一位之和
5. 求斐波那契数列的第N项
6. 汉诺塔
7. 青蛙跳台阶
1. 递归求N的阶乘
//递归求n的阶乘
public class test {//求n的阶乘方法public static int func(int n) {if (n == 1) {return 1;}int tmp = n * func(n-1);return tmp;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();System.out.println(func(n));}
}
2. 按顺序打印一个数字的每一位
例如1234打印出1 2 3 4
//按顺序打印一个数字的每一位
public class test {//顺序打印数字public static void func(int num) {if (num > 9) {func(num / 10);}System.out.print(num % 10 + " ");}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int num = sc.nextInt();func(num);}
}
3. 递归求n的和
//递归求n的和
public class test {//public static int func(int num) {if (num == 1) {return 1;}int sum = num + func(num -1);return sum;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int num = sc.nextInt();System.out.println(func(num));}
}
4. 计算一个数每一位之和
输入一个非负数,返回组成它的数字之和。例如,输入1729,则应该返回1+7+2+9,它的和是19
//计算一个数每一位之和
public class test {//public static int sum(int num) {if (num < 10) {return num;}return num%10 + sum(num/10);}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int num = sc.nextInt();System.out.println(sum(num));}
}
5. 求斐波那契数列的第N项
//求斐波那契数列的第N项
public class test {//递归方式public static int fib1(int n) {if (n ==1 | n == 2) {return 1;}return fib1(n-1) + fib1(n-2);}//迭代方式(非递归)public static int fib2(int n) {if (n == 1 || n ==2) {return 1;}int f1 = 1;int f2 = 1;int f3 = 0;for (int i = 3; i <= n; i++) {f3 = f1 + f2;f1 = f2;f2 = f3;}return f3;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();System.out.println(fib1(n));}
}
6. 汉诺塔
//汉诺塔问题
public class test {//打印移动的情况public void move(char pos1, char pos2) {System.out.println(pos1+"->"+pos2+" ");}//hanoiTower,n为当前盘子个数,pos1为起始位置,pos2中转位置,pos3目的位置public static void hanoiTower(int n, char pos1, char pos2, char pos3) {if(n == 1) {move(pos1, pos2);} else {hanoiTower(n-1, pos1,pos3,pos2);move(pos1,pos3);hanoiTower(n-1,pos2,pos1,pos3);}}public static void main(String[] args) {hanoiTower(1,'A','B','C'); // A->BSystem.out.println();hanoiTower(2,'A','B','C'); // A->C A->C B->ASystem.out.println();hanoiTower(3,'A','B','C'); // A->B A->B C->A A->C B->C B->C A->BSystem.out.println();}
}
7. 青蛙跳台阶
斐波那契数列的变形,第一个是1,第二个是2(斐波那契前两个为1)
//青蛙跳台阶问题
public class test {public static int jumpFloor(int target) {if (target == 1) {return 1;}if (target == 2) {return 2;}return jumpFloor(target - 1) + jumpFloor(target - 2);}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();System.out.println(jumpFloor(n));}
}