LeetCode面试题64.求1+2+…+n

题目要求

算法分析

不让用乘除,不让用for while if else switch case

首先想到递归,递归需要有终止条件,

可以利用&&的特性,左边为false,来屏蔽掉右边的代码,来实现终止功能.

代码展示(C#)

public class Solution {
    public int SumNums(int n) {
        bool flag = n > 0 && (n += SumNums(n - 1)) > 0;
        return n;
    }
}

代码展示(C++)

class Solution {
public:
    int sumNums(int n) {
        n && (n+=sumNums(n-1))>0;
        return n;
    }
};

提交结果

原文地址:https://www.cnblogs.com/KingR/p/13028879.html