面试题64:求1+2+3+.........+n

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

2、思路:不让用乘除和判断,递归的话只能用短路作为终止条件,使用短路法。

3、代码:

public class Solution {
    public int Sum_Solution(int n) {
        int sum=n;
        //n=1时直接返回1
        boolean flag=(sum>0)&&((sum+=Sum_Solution(n-1))>0);
        return sum;
    }
}

猜你喜欢

转载自www.cnblogs.com/guoyu1/p/12216520.html