剑指offer——74求1+2+3+n
题目描述
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
题解:
利用类的构造和析构
利用类的构造和析构
1 //利用类的构造 2 class Temp{ 3 public: 4 Temp() { ++N; sum += N; } 5 static void Reset() { N = 0; sum = 0; } 6 static unsigned int getRes() { return sum; } 7 private: 8 static unsigned int N, sum;//一定得是静态,否则每次创建是会重新赋值 9 }; 10 unsigned int Temp::N = 0; //一定得先初始化 11 unsigned int Temp::sum = 0; 12 13 class Solution { 14 public: 15 int Sum_Solution(int n) { 16 Temp::Reset(); 17 Temp *t = new Temp[n]; 18 delete[]t; 19 t = nullptr; 20 return Temp::getRes(); 21 } 22 }; 23 //利用类的析构 24 class A; 25 A *Array[2]; 26 class A{ 27 public: 28 virtual unsigned int sum(unsigned int n){ 29 return 0; 30 } 31 }; 32 class B :public A { 33 public: 34 virtual unsigned int sum(unsigned int n) { 35 return Array[!!n]->sum(n - 1) + n; 36 } 37 }; 38 int getSum(int n) { 39 A a; 40 B b; 41 Array[0] = &a; 42 Array[1] = &b; 43 return Array[1]->sum(n); 44 } 45 //利用函数指针 46 typedef unsigned int(*fun)(unsigned int); 47 unsigned int Solution3_Teminator(unsigned int n){ 48 return 0; 49 } 50 51 unsigned int Sum_Solution3(unsigned int n){ 52 static fun f[2] = { Solution3_Teminator, Sum_Solution3 }; 53 return n + f[!!n](n - 1); 54 } 55 56 // 利用模板 57 template <unsigned int n> struct Sum_Solution4{ 58 enum Value { N = Sum_Solution4<n - 1>::N + n }; 59 }; 60 61 template <> struct Sum_Solution4<1>{ 62 enum Value { N = 1 }; 63 }; 64 65 template <> struct Sum_Solution4<0>{ 66 enum Value { N = 0 }; 67 };