s-day08--递归求累和的练习
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
package com.inmind.dg02;
|
||||
/*
|
||||
12.递归求累和的练习
|
||||
|
||||
5的累和:5+4+3+2+1 = 15
|
||||
4的累和:4+3+2+1 = 10
|
||||
3的累和:3+2+1 = 6
|
||||
2的累和:2+1 = 3
|
||||
1的累和:1
|
||||
|
||||
求累和的数学规律是 n的累和 = n+(n-1)的累和
|
||||
|
||||
核心思想:递归代码如何编写??
|
||||
1.判断当前是否是结束条件,如果是就结束(return)
|
||||
2.如果不是结束条件,那么按数学规律或者逻辑规律调用自己
|
||||
*/
|
||||
public class Demo10 {
|
||||
public static void main(String[] args) {
|
||||
int result = getLH(100);
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
public static int getLH(int n) {
|
||||
//判断结束条件
|
||||
if (n == 1) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return n+getLH(n-1);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user