美文网首页
64:求1+2+…+n

64:求1+2+…+n

作者: stoneyang94 | 来源:发表于2018-08-28 10:09 被阅读0次

题目64:求1+2+…+n

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

思路

对于剑指Offer书上介绍的四种方法都是C++的解法,不适用于JAVA。

利用&&的短路特性控制base case,递归实现加法。

代码实现

public class _64 {
    public static int Sum(int n) {
        int res = n;
        boolean flag = (n>0)&&((res+=Sum(n-1))>0);//利用&&的短路特性控制base case
        return res;
    }
    public static void main(String[] args) {
        System.out.println("1+2+3 = "+Sum(3));
        System.out.println("1+2+3+4+5 = "+Sum(5));
    }
}

输出:

1+2+3 = 6
1+2+3+4+5 = 15

相关文章

网友评论

      本文标题:64:求1+2+…+n

      本文链接:https://www.haomeiwen.com/subject/rddtwftx.html