算法 &&逻辑与运算的短路特性

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

思路: 由于逻辑与运算具有短路的特性,当不断+到0时,短路返回

class Solution {
public:
    int Sum_Solution(int n) {
        int ans=n;
        ans && (ans+=Sum_Solution(n-1));
        return ans;
    }
};

可以看到,递归不断向下累加,直到 ans=0时,直接返回0 递归调用栈开始不断累加返回,最终求得1+2...+n

进阶:求 2+3+4...+n

只要拼凑出 1+2....+n 即可  即  ans-1 >=0

猜你喜欢

转载自blog.csdn.net/qq_33369979/article/details/88363218