1.实现1到100的和,用递归实现
public class RecursionTest {
public static void main(String[] args) {
System.out.println(diGui(100));// 5050
}
public static int diGui(int n) {
int sum;
if (n == 1)
return 1;
else {
sum = n + diGui(n - 1);
return sum;
}
}
}
2.递归实现1到100的阶乘
public class RecursionTest {
public static void main(String[] args) {
System.out.println(diGui(5));// 120 注意如果求100的阶乘那么就不能用int或者long,计算后的结果数值过大程序无法返回,一般情况会返回0要用BigInteger
}
public static int diGui(int n) {
int sum;
if (n == 1)
return 1;
else {
sum = n * diGui(n - 1);
return sum;
}
}
}