zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

剑指 Offer 64. 求1+2+…+n

2023-02-18 16:35:25 时间

题目:

 

 

思路:

【1】思路一:这种一般可以转换为函数替代的方式,如1+2+3+..+n,在数学上可以使用(1+n)*n/2,也就是平均数乘以个数得到最终结果。

【2】思路二:便是采用常规的循环和递归方式按照寻常的逻辑进行累加,其中需要判断的地方采用其他方式替换。

代码展示:

public class Offer {
    public static void main(String[] args) {
        Random random = new Random();
        int arr = random.nextInt(10000)+1;
        System.out.println("参数:"+arr);
        System.out.println(Method1(arr));
    }

    //思路一的体现
    public static int Method1(int arr){
        int result = 0;
        result = (1+arr)*arr/2;
        return result;
    }

    //思路二:也就是常见的循环或递归思想
    //但这种是被禁用的
    public static int Method2(int arr){
        int result = 0;
        for (int i = 1;i<=arr;i++){
            result += i;
        }

        return result;
    }
    //方案三:思路二的变种,因为循环函数被禁用情况大概率循环是不能用了,但是递归可以
    //但是对于递归要考虑的就是判断的情况,所以采用&&来替代if语句
    public static int Method3(int arr){
        int result = arr;

        boolean flag = arr>0 && (result=result+Method3(result-1))>0;
        
        return result;
    }
}