【题目描述】
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
【思路】
利用构造函数和静态变量及函数
【代码】
class Father
{
public:
Father()
{
n++;
sum += n;
}
static void clear()
{
n = 0;
sum = 0;
}
static int Getsum()
{
return sum;
}
private:
static unsigned int n;
static unsigned int sum;
};
unsigned int Father::n = 0;
unsigned int Father::sum = 0;
class Solution {
public:
int Sum_Solution(int n) {
Father::clear();
Father *tmp = new Father[n];
delete [] tmp;
tmp = NULL;
return Father::Getsum();
}
};