[每日一题]15:求1+2+3+...+n

135 阅读1分钟

文章目录


题目描述

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

示例 1:

输入: n = 3
输出: 6

示例 2:

输入: n = 9
输出: 45

题解思路

方法一:递归

  • 题目中for、while关键字已经被禁止使用,则可以利用递归进行运算
  • 利用逻辑与的短路特性实现递归终止

解题代码

class Solution {
public:
    int sumNums(int n) {
        int tmp = n;
        tmp && (tmp += sumNums(n - 1));
        return tmp;
    }
};
class Solution {
public:
    int sumNums(int n) {
        return n == 0 ? 0 : n +sumNums(n-1);
    }
};

方法二:构造函数

  • 找两个静态成员变量,通过构造函数的方式来解决

解题代码

#include <iostream>
using namespace std;

class test {
public:
	static int s_m_tmp;
	static int s_m_sum;

	test() {
		s_m_tmp++;
		s_m_sum += s_m_tmp;
	}
};

int test::s_m_tmp = 0;
int test::s_m_sum = 0;

int main() {
	test* t = new test[10];
	cout << test::s_m_sum;

	delete[] t;
	return 0;
}

如有不同见解,欢迎留言讨论