求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
java版
public class Solution {
public int Sum_Solution(int n) {
int ans = n;
boolean t=((ans!=0) && (ans += Sum_Solution(n - 1))<-1);
return ans;
}
}
C++版
class Solution {
public:
int Sum_Solution(int n) {
int ans = n;
ans && (ans += Sum_Solution(n - 1));
return ans;
}
};
boolean t=((ans!=0) && (ans += Sum_Solution(n - 1))<-1);
注意:在java中,不能自动转bool,所以这个位置需要语句。后边的 <-1条件可以为任意条件,因为在递归的过程中执行不到,此位置仅仅是保持bool的格式。