求1+2+3+...+n的非常规方法

题目描述

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
 
思路:
  1、利用构造函数,定义静态变量
 1 class Add
 2 {
 3 public:
 4     Add()
 5     {
 6         ++n;
 7         sum=sum+n;
 8     }
 9     static int getSum()
10     {
11         return sum;
12     }
13     static void clear()
14     {
15         n=0;
16         sum=0;
17     }
18 private:
19     static int n;
20     static int sum;
21 };
22 int Add::n=0;
23 int Add::sum=0;
24 class Solution {
25 public:
26     int Sum_Solution(int n) {
27         Add *p=new Add[n];
28         int result=Add::getSum();
29         Add::clear();//每次算完后要清零
30         delete []p;
31         return result;
32     }
33 };

  2、利用虚函数

 1 class A
 2 {
 3 public:
 4     virtual int getSum(int n)
 5     {
 6         return 0;
 7     }
 8 };
 9 A *Array[2];
10 class B : public A
11 {
12 public:
13     virtual int getSum(int n)
14     {
15         return Array[!!n]->getSum(n-1)+n;
16     }
17 };
18 class Solution {
19 public:
20     int Sum_Solution(int n) {
21         A a;
22         B b;
23         Array[0]=&a;
24         Array[1]=&b;
25         return Array[1]->getSum(n);
26     }
27 };

  3、利用函数指针

 1 typedef int (*fun)(int n);
 2 fun Array[2];
 3 int add1(int n)
 4 {
 5     return 0;
 6 }
 7 int add2(int n)
 8 {
 9     return Array[!!n](n-1)+n;
10 }
11 class Solution {
12 public:
13     int Sum_Solution(int n) {
14         Array[0]=add1;
15         Array[1]=add2;
16         return Array[1](n);
17     }
18 };

  4、利用模板类

 1 #include<iostream>
 2 using namespace std;
 3 template<int n>
 4 class A
 5 {
 6 public:
 7     enum Value{
 8         N=A<n-1>::N+n
 9     };
10 };
11 template<>
12 class A<0>
13 {
14 public:
15     enum Value{
16         N=0
17     };    
18 };
19 int main()
20 {
21     cout<<A<100>::N<<endl;//不能动态输入,必须是在编译时就能确定的常量
22     return 0;
23 }

 

posted @ 2018-02-01 14:11  jeysin  阅读(210)  评论(0编辑  收藏  举报