简单地说:递归就是方法自己调用自己,每次调用时传入不同的变量,递归有助于编程者解决复杂的问题,同时可以让代码更简洁
阶乘问题
3!=1*2*3;
n! = 1*2*3*4.....*n;
class JieCheng{
public int jieCheng(int num){
if(num > 1){
return jieCheng(num-1)*num;
}else{
return 1;
}
}
}
阶乘累和
求1!+2!+3!+...+5!的和
class JieCheng{
public int jieCheng(int number){
if(number > 1){
return jieCheng(number-1)*number;
}else{
return 1;
}
}
//计算各阶层的和
public int jieChengSum(int number){
if (number == 0||number==1) {
return 1;
} else{
int sum =0;
sum += jieCheng(number);
return sum+jieChengSum(number-1);
}
}
}
public class Text01 {
public static void main(String[] args) {
JieCheng jiecheng = new JieCheng();
System.out.println(jiecheng.jieCheng(5));
System.out.println(jiecheng.jieChengSum(5));
}
}
运行结果:
120
153