有这样一道C/C++题:求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
还有多少种解法?对于这个问题限制了我们常用的求解方式,目的是想让我们另辟蹊径。那么我们只有硬着头皮找各种方式来应对此题,下面为大家带来几个来自网友们的方法,供我们共同学习:
1、利用了&&的短路特性:即当&&(与)的左边为假时整个表达式为假,右边的不用再计算了;下边附上解决代码:
class
Solution {
public
:
int
Sum_Solution(
int
n) {
int
sum = n;
sum && (sum += Sum_Solution(n - 1));
return
sum;
}
};
|
1)利用逻辑与的短路特性实现递归终止。
2)
当n==
0
时,
sum && (sum += Sum_Solution(n - 1))
只执行前面的判断,为
false
,然后直接返回
0
;
3)
当n>
0
时,执行sum+=Sum_Solution(n-
1
),实现递归计算Sum_Solution(n)。
2、用公式是不可以的,公式里有乘法!!实现乘法可以用sizeof多维数组,
class
Solution {
public
:
int
Sum_Solution(
int
n) {
bool
a[n][n+1];
return
sizeof
(a)>>1;
}
};
3、当有人说用公式不可以的时候,别人果断的用其他方式利用了公式,而且只需要一行(惊呆):
class Solution {
public :int Sum_Solution(int n) {
return ( (int) (.pow(n, 2)+n))>>1;
}
}
4、
用异常退出递归
public class Solution {
public int Sum_Solution(int n) {
return sum(n);
}
int sum(int n){
try{
int i = 1%n;
return n+sum(n-1);
}
catch(Exception e){
return 0;
}
}
}
class Solution {
public:
int Sum_Solution(int n) {
//return n*(n+1)/2;
return multi(n, n + 1) >> 1;
}
int multi(int a, int b){
// we can guarantee that both a and b is positive integers
int res = int(pow(10, log10(a) + log10(b))+0.5);
return res;
}
};