1、递归求 N 的阶乘
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println(dg(a));
}
public static int dg(int x) {
if (x == 1) {
return 1;
}
return x * dg(x - 1);
}
}
2、递归求 1 + 2 + 3 + … + 10
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println(addDg(10));
}
public static int addDg(int x) {
if (x == 1) {
return 1;
}
return x + addDg(x - 1);
}
}
3、按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) (递归)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
everyNub(a);
}
public static void everyNub(int x) {
if (x > 10) {
everyNub(x / 10);
}
System.out.println(x % 10);
}
}
4、写一个递归方法,输入一个非负整数,返回组成它的数字之和.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println(addeveryNub(a));
}
public static int addeveryNub(int x) {
if (x < 10) {
return x;
}
return x % 10 + addeveryNub(x / 10);
}
}
5、递归求斐波那契数列的第 N 项
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println(fb(a));
}
public static int fb(int x) {
if (x == 1 || x == 2) {
return 1;
}
return fb(x - 1) + fb(x - 2);
}
}