剑指Offer-47.求1+2+3+...+n(C++/Java)

题目:

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

分析:

利用短路与来判断n是否大于0,从而实现递归求和。

程序:

C++

class Solution {
public:
    int Sum_Solution(int n) {
        int res = n;
        bool flag = (n > 0) && (res += Sum_Solution(n-1));
        return res;
    }
};

Java

public class Solution {
    public int Sum_Solution(int n) {
        int res = n;
        boolean flag = (n > 0) && (res += Sum_Solution(n-1)) > 0;
        return res;
    }
}
posted @ 2019-12-23 13:43  silentteller  阅读(328)  评论(0编辑  收藏  举报