求1+2+…+n(思维发散)

1、题目

这里写图片描述

思路

使用递归计算累加,利用逻辑与的短路特性终止递归。逻辑与的短路特性 : A&&B,A为0时不执行B。

class Solution {
public:
    // 逻辑与的短路特性终止递归
    int Sum_Solution(int n) 
    {
        int res = n;
        res && (res += Sum_Solution(n - 1));//res为0时为假
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_35433716/article/details/81837415