剑指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;
    }
}
原文地址:https://www.cnblogs.com/silentteller/p/12083321.html