剑指offer——利用逻辑与的短路操作实现1到n的求和

剑指offer——利用逻辑与的短路操作实现1到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;
        boolean ans=(n>0) && (sum += Sum_Solution(n-1))>0;
        return sum;
    }
}

4 其它思路:利用异常抛出结束递归

5 答案

public class Solution {
    public int Sum_Solution(int n) {
        return sum(n);
    }
    private int sum(int n){
        try{
            int i=1;
            i=i/n;
            return n+sum(n-1);
        }catch(Exception e){
            return 0;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yangxingpa/article/details/80330705