题目描述

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
 
题解:
  利用类的构造和析构
 //利用类的构造
class Temp{
public:
Temp() { ++N; sum += N; }
static void Reset() { N = ; sum = ; }
static unsigned int getRes() { return sum; }
private:
static unsigned int N, sum;//一定得是静态,否则每次创建是会重新赋值
};
unsigned int Temp::N = ; //一定得先初始化
unsigned int Temp::sum = ; class Solution {
public:
int Sum_Solution(int n) {
Temp::Reset();
Temp *t = new Temp[n];
delete[]t;
t = nullptr;
return Temp::getRes();
}
};
//利用类的析构
class A;
A *Array[];
class A{
public:
virtual unsigned int sum(unsigned int n){
return ;
}
};
class B :public A {
public:
virtual unsigned int sum(unsigned int n) {
return Array[!!n]->sum(n - ) + n;
}
};
int getSum(int n) {
A a;
B b;
Array[] = &a;
Array[] = &b;
return Array[]->sum(n);
}
//利用函数指针
typedef unsigned int(*fun)(unsigned int);
unsigned int Solution3_Teminator(unsigned int n){
return ;
} unsigned int Sum_Solution3(unsigned int n){
static fun f[] = { Solution3_Teminator, Sum_Solution3 };
return n + f[!!n](n - );
} // 利用模板
template <unsigned int n> struct Sum_Solution4{
enum Value { N = Sum_Solution4<n - >::N + n };
}; template <> struct Sum_Solution4<>{
enum Value { N = };
}; template <> struct Sum_Solution4<>{
enum Value { N = };
};
05-11 21:49