题目:求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
解法一:
思路:递归求和。
class Solution {
public:
int Sum_Solution(int n) {
int sum =n;
sum &&(sum+=Sum_Solution(n-1));
return sum;
}
};
解法二:
思路:利用构造函数求解。我们先定义一个类,接着创建n个该类型的实例,那么这个构造函数将会被调用n次,我们可以将累加的代码放到构造函数里面。
class Temp
{
public:
Temp(){ ++N; Sum += N; }
static void Reset(){ N = 0; Sum = 0; }
static unsigned int GetSum(){ return Sum; }
private:
static unsigned int N;
static unsigned int Sum;
};
unsigned int Temp::N = 0;
unsigned int Temp::Sum = 0;
class Solution {
public:
int Sum_Solution(int n) {
Temp::Reset();
Temp* a = new Temp[n];
delete[]a;
a = nullptr;
return Temp::GetSum();
}
};
解法三:
思路:利用虚函数求解。
class A;
A *Array[2];
class A
{
public:
virtual unsigned int Sum(unsigned int n)
{
return 0;
}
};
class B :public A
{
public:
unsigned int Sum(unsigned int n)
{
return Array[!!n]->Sum(n - 1) + n;
}
};
class Solution {
public:
int Sum_Solution(int n) {
A a;
B b;
Array[0] = &a;
Array[1] = &b;
int value = Array[1]->Sum(n);
return value;
}
};