题目描述:
解题思路:
首先定义res存储1加到n的和。总体还是使用递归的思想,但是因为不能使用if条件判断递归跳出条件,所以这里使用&&操作跳出循环。当n大于1的时候,&&前面为true,所以可以执行sum(n - 1),如果&&前面为false,所以就跳出循环。
代码实现:
class Solution {
int res = 0;
public int sumNums(int n) {
boolean x = n > 1 && sumNums(n - 1) > 0;
res += n;
return res;
}
}
执行结果: