一、题目
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A ? B : C)。
二、思路及代码
方法一:高斯求法
1 + 2 + 3 + . . . + n = n ( 1 + n ) 2 = n 2 + n 2 1 + 2 + 3 + ... + n = \frac{n(1 + n)}{2} = \frac{n^2 + n}{2} 1+2+3+...+n=2n(1+n)=2n2+n
除以 2 可以使用右移运算(>>)来实现。
代码如下:
public class Solution {
public int Sum_Solution(int n) {
return (int)(Math.pow(n, 2) + n) >> 1;
}
}
方法二:递归
n = 1 时,sum(1) = 1;
n = 2 时,sum(2) = 2 +sum(1);
n = 3 时,sum(3) = 3 + sum(2);
… …
所以,sum(n) = n + sum(n - 1)。
public class Solution {
public int Sum_Solution(int n) {
if(n == 1)
return 1;
return Sum_Solution(n - 1) + n;
}
}