求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
示例 1:
输入: n = 3
输出: 6
示例 2:
输入: n = 9
输出: 45
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/qiu-12n-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
不让用控制结构if、while、for和条件判断语句
考虑到for循环的另一种递归实现,如果n为1返回1
不为1就返回n-1作为参数的函数加上1的和
直到递归到返回1为止
代码如下:
class Solution {
public:
int sumNums(int n) {
if(n==1)return 1;
return sumNums(n-1)+n;
}
};