求1+2+…+n, 要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。

方法一:利用构造函数和静态数据成员

[cpp] view plaincopy
 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Temp  
  5. {  
  6. public:  
  7.     Temp()  
  8.     {  
  9.         ++N;  
  10.         Sum+=N;  
  11.     }  
  12.   
  13.     static void Reset()  
  14.     {  
  15.         N=0;  
  16.         Sum=0;  
  17.     }  
  18.   
  19.     static int GetSum()  
  20.     {  
  21.         return Sum;  
  22.     }  
  23. private:  
  24.     static int N;  
  25.     static int Sum;  
  26. };  
  27.   
  28. int Temp::N=0;  
  29. int Temp::Sum=0;  
  30.   
  31. int solution_Sum(int n)  
  32. {  
  33.     Temp::Reset();  
  34.   
  35.     Temp *a=new Temp[n];  
  36.     delete []a;  
  37.     a=0;  
  38.   
  39.     return Temp::GetSum();  
  40. }  
  41.   
  42. int main()  
  43. {  
  44.     cout<<solution_Sum(100)<<endl;  
  45.     return 0;  
  46.   
  47. }  

方法二:利用虚函数

[cpp] view plaincopy
 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class A;  
  5. A* Array[2];  
  6.   
  7. class A  
  8. {  
  9. public:  
  10.     virtual int Sum(int n)  
  11.     {  
  12.         return 0;  
  13.     }  
  14. };  
  15.   
  16. class B:public A  
  17. {  
  18. public:  
  19.     virtual int Sum(int n)  
  20.     {  
  21.         return Array[!!n]->Sum(n-1)+n;  
  22.     }  
  23. };  
  24.   
  25. int solution2_Sum(int n)  
  26. {  
  27.     A a;  
  28.     B b;  
  29.     Array[0]=&a;  
  30.     Array[1]=&b;  
  31.   
  32.     int value=Array[1]->Sum(n);  
  33.   
  34.     return value;  
  35. }  
  36.   
  37. int main()  
  38. {  
  39.     cout<<solution2_Sum(100)<<endl;  
  40.     return 0;  
  41. }  

利用函数指针

[cpp] view plaincopy
 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. typedef int (*fun)(int);  
  5.   
  6. int solution_f1(int i)  
  7. {  
  8.     return 0;  
  9. }  
  10.   
  11. int solution_f2(int i)  
  12. {  
  13.     fun f[2]={solution_f1, solution_f2};  
  14.     return i+f[!!i](i-1);  
  15. }  
  16.   
  17. void main()  
  18. {  
  19.     cout<<solution_f2(100)<<endl;  
  20. }  


 


三。利用&&的短路特性

[cpp] view plaincopy
 
    1. #include <stdio.h>  
    2. #include <stdlib.h>  
    3. #include <string.h>  
    4.   
    5. int add_fun(int n, int &sum)  
    6. {  
    7.     n && add_fun(n-1, sum);  
    8.     return (sum+=n);  
    9. }  
    10.   
    11. int main()  
    12. {  
    13.     int sum=0;  
    14.     int n=100;  
    15.   
    16.     printf("1+2+3+...+n=%d\n",add_fun(n, sum));  
    17.   
    18.     return 0;  
    19. }  
原文地址:https://www.cnblogs.com/lzmfywz/p/3036370.html