剑指Offer:求和1~n

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

利用逻辑与(&&)的短路特点,当前面为假时,后面不计算。因此,构成了递归结束的条件,回到递归栈顶的时候,即得到了求和的结果。

    int Sum_Solution(int n) {
        int ans = n;
        ans && (ans += Sum_Solution(n - 1));
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/La745739773/article/details/89228309