Skip to content
本页目录

64-求1+2+…+n

题目描述

https://leetcode.cn/problems/qiu-12n-lcof

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

示例 1:

输入: n = 3
输出: 6

示例 2:

输入: n = 9
输出: 45

限制:

1 <= n <= 10000

思路分析

基本思路: 递归解决问题,不能使用if判断 但是可以利用 C# 的 逻辑运算符,&& 如果左边条件已经失败了,后面的计算步骤就不会再算 这样就可以作为终止条件了,前面满足的时候,后面继续运算 n += SumNum(n-1) 直到 n == 0 的时候停止 实在不能理解就强行记住

实现代码

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

思路2:使用 try catch 模拟

创建一个只有1个数的数组test,输入n的时候,由 test[n] 会越界,那么进入 catch, catch就递归调用下一层。 直到 n = 0 的时候,符合条件 return test[0] = 0,结束递归。

csharp
public class Solution{
    int[] test = new int[]{0};
    public int SumNums(int n){
        try{
            return test[n];
        }
        catch{
            return n + SumNums(n-1);
        }
    }
}

复习:20220509

csharp
public class Solution {
    public int SumNums(int n) {
        int[] arr = new int[1];
        arr[0] = 0;
        try{
            return arr[n];
        }
        catch{
            return n + SumNums(n-1);
        }
    }
}

Released under the MIT License.