zerofly's Blog

努力不一定成功,但不努力一定不会成功

0%

求1+2+3+...+n


题目描述

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

解题思路

其中两种思路:

  • 直接使用求和公式 s = (1 + n) * n / 2
  • 使用递归的方法

代码

1
2
3
4
5
6
7
8
9
10
11
// 公式方法
class Solution
{
public:
int Sum_Solution(int n)
{
int sum = 0;
sum = (1 + n) * n /2;
return sum;
}
};
1
2
3
4
5
6
7
8
9
10
11
// 递归方法
class Solution
{
public:
int Sum_Solution(int n)
{
int sum = n;
sum && (sum += Sum_Solution(--n)); // 当n减到 0时即为递归停止的条件,注意是 --n,不是n--
return sum;
}
};

参考博文链接:https://cuijiahua.com/blog/2018/01/basis_47.html

文章作者:zerofly

发布时间:2020年06月02日 - 21:06

原始链接:http://zeroflycui.github.io/e799159.html

许可协议: 转载请保留原文链接及作者。