剑指offer系列之四十六:求1到n的和

来源:互联网 发布:华山派 知乎 编辑:程序博客网 时间:2024/06/08 14:20

题目描述

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

如果不能使用上面的操作,那么只能使用递归操作了。使用递归操作的思路是让函数不断调用自己,每调用一次值就减少1,这样完成了递归操作。还有一个问题是如何实现n范围的判断呢?注意到递归调用的n的值最小是1,所以可以通过逻辑与运算,判断是否递归到1。如果递归调用到1,那么递归就结束,并返回最后的结果。下面是这样思路的实现代码(已被牛客AC):

package com.rhwayfun.offer;public class SumOfN {    private int result = 0;    public int Sum_Solution(int n) {        calc(n);        return result;    }    private boolean calc(int n) {        result += n;        return n != 0 && calc(n - 1);    }    public static void main(String[] args) {        int res = new SumOfN().Sum_Solution(10);        System.out.println(res);    }}
0 0