《剑指 Offer》——47、求 1+2+3+4+···+n

1. 本题知识点

数学

2. 题目描述

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

3. 解题思路

我们可以考虑一下有哪些思路:

  1. 可以使用求和公式,但要求不能使用乘除法,所以这个思路不行
    s u m = n ∗ ( 1 + n ) 2 sum=\frac{n*(1+n)}{2} sum=2n(1+n)

  2. 可以使用循环,但要求不能使用 for、while,所以这个思路不行

    public int Sum_Solution(int n) {
          
          
        int sum = 0;
        for (int i = 1; i <= n; i++) {
          
          
            sum += i;
        }
        return sum;
    }
    
  3. 可以使用递归,但要求不能使用 if,所以这个思路不行。

    public int Sum_Solution(int n) {
          
          
        if (n == 1) {
          
          
            return 1;
        }
        return n + Sum_Solution(n - 1);
    }
    

但我们能不能将 if 换掉成的别的东西呢?于是想到了 &&(短路与)

比如,A && B

  • 当 A 为 true 时,则会执行 B;
  • 当 A 为 false 时,则不会执行 B

这样就达到了条件判断的效果

4. 代码

public class Solution {
    
    
    public int Sum_Solution(int n) {
    
    
        boolean x = (n > 1) && (n += Sum_Solution(n - 1)) > 0;
        return n;
    }
}

猜你喜欢

转载自blog.csdn.net/bm1998/article/details/108024443