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

剑指 Offer 64. 求1+2+…+n

难度中等266收藏分享切换为英文接收动态反馈

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

示例 1:

输入: n = 3
输出: 6

示例 2:

输入: n = 9
输出: 45

限制:

  • 1 <= n <= 10000
class Solution {
public:
    int sumNums(int n) {
bool a[n][n+1];//此处一定要记住:不能是int类型,因为sizeof(int)是4;--->此处注意;
return sizeof(a)>>1;
    }
};

没说用加减,只说不能用乘除,那么[一一相加,有规律有截止条件]---->可以用递归;(此处最容易想到;)[for循环可以用递归来代替]

class Solution {
public:
    int sumNums(int n) {
if(n==0)return 0;
int sum=n+sumNums(n-1);
return sum;

    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45929885/article/details/113815472