求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例 1:
输入: n = 3
输出: 6
示例 2:
输入: n = 9
输出: 45
这题可以加深短路的概念
详情可查&&与&&,||和|的区别
正常思路
class Solution {
public int sumNums(int n) {
return n == 0 ? 0 : n + sumNums(n - 1);
}
}
但不能用判断条件(A?B:C)
可以利用&&短路机制
class Solution {
public int sumNums(int n) {
//b并无其他作用,只是为了引出&&
//当n>0为真时,n+=正常执行
//当n>0为假时,由于&&左边为false,&&右边便不会执行
//返回 n
boolean b = n>0 && (n+=sumNums(n-1)) >0;
return n;
}
}
评论区中的脑洞大开代码!
class Solution {
int[] test=new int[]{0};
public int sumNums(int n) {
try{
return test[n];
}catch(Exception e){
return n+sumNums(n-1);
}
}
}
源自力扣用户Lucien
侵删