new 求1+2+。。。。+n

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/mengmengkuaipao/article/details/102751505

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

思路

考研发散思维和知识面的宽度,以及对编程技术理解的深度

1.。。n的和除了用公式n(n+1)/2,无外乎循环和递归两种思路

  1. 循环,要用for 、while
  2. 递归 要有判断条件if

都不行

用 && 短路

需利用逻辑与的短路特性实现递归终止。 2.当n==0时,(n>0)&&((sum+=Sum_Solution(n-1))>0)只执行前面的判断,为false,然后直接返回0;

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

时O(n)

利用Math实现 n(n+1)

public class Solution {
    public int Sum_Solution(int n) {
        return (int)(Math.pow(n,2)+n)>>1;
    }
}

n(n+1)/2 递归实现n(n+1)

猜你喜欢

转载自blog.csdn.net/mengmengkuaipao/article/details/102751505
今日推荐