求1+2+…+n变态问题的两个很棒的解法

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

第一种方法:

 

 1 class Sum
 2 { 
 3 public: 
 4   Sum() 
 5   { 
 6          n++; 
 7          sum+=n;    
 8   } 
 9   void Result()
10   {
11     cout<<sum<<endl;
12   }    
13 private: 
14   static int sum=0;   //类中的静态变量是属于类的,不属于某个对象!不能在定义对象时对变量初始化!
15                 //不能用构造函数来初始化!而且使用时应加上类名,而不是对象。 
16   static int n=0;  
17  };
18  
19 int main() 
20 {
21     Sum *S = new Sum[100];
22     S -> Result();
23     delete S;
24     return 0;
25 }

 

第二种方法:

 

 1 int Sum( int n )
 2 {
 3     int i = 1;
 4     ( n>1 ) && ( i = Sum( n-1 )+n );
 5     return i;
 6 }

posted on 2012-04-06 19:19  NLP新手  阅读(467)  评论(0编辑  收藏  举报

导航