Fork me on GitHub

Sum of the first n consecutive integers

问题

For 1 + 2 + 3 +… +n, you cannot use the multiplication/division, for, while, if, else, switch, case and other keywords and conditional judgment statement (A? B, C).

该题翻译过来就是求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。以下是给出的C解决方案

解决方案

**思路:让其从最后一个数开始相加,直到n为0,则加完

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int i = 0;
//辅助函数求和保存在i中
int Sum(int n )
{
i = i + n;
n--;
return Sum_Solution(n);
}
//函数入口
int Sum_Solution(int n) {

return n==0 ? i : Sum(n);
}
};

本文标题:Sum of the first n consecutive integers

文章作者:LiuXiaoKun

发布时间:2018年10月06日 - 15:10

最后更新:2018年10月06日 - 15:10

原始链接:https://LiuZiQiao.github.io/2018/10/06/求前n个数的和/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%