30. 求 1+ 2 + 3 + ... + n(不能使用乘除法、循环、if、switch)

1. 递归计算求和

package com.fy;

public class T4 {
    
    
    public static void main(String[] args) {
    
    
        //创建对象
        T4 s = new T4();
        System.out.println(s.sum(100));
    }
    //sum方法
    public int sum(int n) {
    
    
        //增加判断语句,如果n为1,不添加if语句会进入死循环,进而栈溢出
        if (n == 1) {
    
    
            return 1;
        }
        return n + sum(n - 1);
    }
}


1

猜你喜欢

转载自blog.csdn.net/zhu_fangyuan/article/details/108739306
今日推荐