一个简单的Java递归算法
5的递归
public class Recursion {
public static void main(String[] args) {
System.out.println(flag(5));
}
static int flag(int temp){
if (temp==1){
return 1;
}else if (temp==2){
return 2;
}else {
return temp*flag(temp-1);
}
}
}
任意正整数的递归
public class Recursion {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int temp=sc.nextInt();
System.out.println(flag(temp));
}
static int flag(int temp){
if (temp==1){
return 1;
}else if (temp==2){
return 2;
}else {
return temp*flag(temp-1);
}
}
}