求1+2+3+...+n,要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句

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

[cpp]  view plain copy
  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 plain copy
  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 plain copy
  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 plain copy
  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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值