每天一道算法题(1) ——不用乘除法求和1+2+…+n


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


方法1:使用函数指针。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. typedef int (*function)(int);  
  2. int func1(int n){  
  3.     return 0;  
  4. }  
  5. int func2(int n){  
  6.     function f[2]={func1,func2};  
  7.     return n+f[!!n](n-1);  
  8. }  
  9. void main(){  
  10.     cout<<func2(10);  
  11. }  



  方法2:使用构造函数。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class test{  
  2.     static int N;  
  3.     static int sum;  
  4. public :  
  5.     test(){sum+=++N;}  
  6.     static void reset(){N=sum=0;}  
  7.     static int getSum(){return sum;}  
  8. };  
  9. int test::N = 0;  
  10. int test::sum = 0;  
  11.   
  12. void main(){  
  13.     test::reset();  
  14.     test *p=new test[10];  
  15.     cout<<test::getSum();  
  16.     delete []p;  
  17. }  


方法3:使用虚函数的编译多态性

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class A{  
  2.   public:  
  3.     virtual int sum(int n){return 0;};  
  4. };  
  5. class B:public A  
  6. {  
  7.     public:  
  8.     int sum(int n){  
  9.        A a;B b;  
  10.        A *p[2]={&a,&b};  
  11.        return n+p[!!(n-1)]->sum(n-1);}  
  12. };  
  13.   
  14. void main(){  
  15.     B b;  
  16.     cout<<b.sum(10);   
  17. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值