题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
方法一:构造函数
class helper {
public:
helper(){
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 helper::n = 0;
unsigned int helper::sum = 0;
class Solution {
public:
int Sum_Solution(int n) {
helper::reset();
helper *s = new helper[n];
int res = helper::getSum();
delete[]s;
return res;
}
};
方法二:虚函数
class base;
base * array[2];
class base{
public:
virtual unsigned int sum(unsigned int n){
return 0;
}
};
class derive :public base{
public:
virtual unsigned int sum(unsigned int n){
return array[!!n]->sum(n - 1) + n;
}
};
class Solution {
public:
int Sum_Solution(int n) {
base a;
derive b;
array[0] = &a;
array[1] = &b;
return b.sum(n);
}
};
int main(){
Solution s;
cout<<s.Sum_Solution(10);
return 0;
}
方法三:函数指针
typedef unsigned int(*fun)(unsigned int);
unsigned int teminator(unsigned int n){
return 0;
}
unsigned int recursion(unsigned int n){
static fun f[2] = { teminator, recursion };
return n+f[!!n](n-1);
}
方法四:短路特征
class Solution {
public:
int Sum_Solution(int n) {
int res = n;
res && (res += Sum_Solution(n - 1));
return res;
}
};