首页 > 技术文章 > 方法的递归调用

dupeilin 2020-05-12 10:28 原文

/*比如:计算1~5的和
1+2+3+4+5
*/
/*比如:计算1~5的和
   1+2+3+4+5
*/

public static void main(String[] args) {
    int n = 4;
    int revalue = sum(n);
    int add;
    System.out.println(revalue);  //15
}
public static int sum(int n ){
    if(n == 1){
    return 1;
    }
    int revalue = sum(n -1);
    int result = n+ revalue;
    return result;
}

  精简版本

  public static void main(String[] args) {
        int n = 4;
        int revalue = sum(n);
        int add;
        System.out.println(revalue);  //15
    }
    public static int sum(int n ){
        if(n == 1){
        return 1;
        }
        int revalue = sum(n -1);
        int result = n+ revalue;
        return result;
    }

 

推荐阅读