本文共 778 字,大约阅读时间需要 2 分钟。
数学
求 1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
我们可以考虑一下有哪些思路:
可以使用求和公式,但要求不能使用乘除法,所以这个思路不行
s u m = n ∗ ( 1 + n ) 2 sum=\frac{n*(1+n)}{2} sum=2n∗(1+n)可以使用循环,但要求不能使用 for、while,所以这个思路不行
public int Sum_Solution(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum;}
可以使用递归,但要求不能使用 if,所以这个思路不行。
public int Sum_Solution(int n) { if (n == 1) { return 1; } return n + Sum_Solution(n - 1);}
但我们能不能将 if 换掉成的别的东西呢?于是想到了 &&(短路与)。
比如,A && B
这样就达到了条件判断的效果
public class Solution { public int Sum_Solution(int n) { boolean x = (n > 1) && (n += Sum_Solution(n - 1)) > 0; return n; }}
转载地址:http://tyjvb.baihongyu.com/