剑指offer -- 求1+2+3+4+...+n

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/86774125
  • 描述:求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
  • 分析:既然不能使用乘除法及判断操作,很容易想到递归,代码如下:
class Solution {
public:
    int Sum_Solution(int n) {
        if (n <= 0) return 0;
        flag++;
        return flag + Sum_Solution(n-1);
    }
private:
    int flag = 0;
};

现在的任务是将if操作改写。

  • 思路一:用逻辑与的短路特性来将if改写。
    1.如果n<=0,则n>0为false(短路),不执行res = flag + Sum_Solution(n-1)操作。
    2.如果n>0,则n>0为true,执行res = flag + Sum_Solution(n-1)。
class Solution {
public:
    int Sum_Solution(int n) {
        flag++;
        bool judge = (n > 0) && ((res = flag + Sum_Solution(n-1)) > 0);
        return res;
    }
private:
    int flag = 0;
    int res = 0;
};

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/86774125