【面试题046】求1+2+...+n

【面试题046】求1+2+...+n
题目:
    求1+2+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
 
思路一:
    利用构造函数求解。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 
#include <iostream>

using  namespace std;

class Temp
{
public:
    Temp()
    {
        ++ N;
        Sum += N;
    }

     static  void Reset()
    {
        N =  0;
        Sum =  0;
    }
     static  unsigned  int GetSum()
    {
         return Sum;
    }
private:
     static  unsigned  int N;
     static  unsigned  int Sum;
};

unsigned  int Temp::N =  0;
unsigned  int Temp::Sum =  0;

unsigned  int Sum_Solution1( unsigned  int n)
{
    Temp::Reset();

    Temp *a =  new Temp[n];
     delete []a;
    a =  NULL;

     return Temp::GetSum();
}

int main()
{
    cout << Sum_Solution1( 100) << endl;
     return  0;
}
 
思路二:
    利用虚函数求解。利用多态来实现的!
    对!!n连续两次取反运算,那么非0的n转换成了true,0转换成false。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 
#include <iostream>

using  namespace std;


class A;
A *Array[ 2];

class A
{
public:
     virtual  unsigned  int Sum( unsigned  int n)
    {
         return  0;
    }
};

class B :  public A
{
public:
     virtual  unsigned  int Sum( unsigned  int n)
    {
         return Array[!!n]->Sum(n -  1) + n;
    }
};


int main()
{
    A a;
    B b;
    Array[ 0] = &a;
    Array[ 1] = &b;
     int value = Array[ 1]->Sum( 100);
    cout << value << endl;
     return  0;
}
 
思路三:
    利用函数指针求解。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
#include <iostream>

using  namespace std;


typedef  unsigned  int (*fun)( unsigned  int);

unsigned  int Solution3_Teminator( unsigned  int n)
{
     return  0;
}

unsigned  int Sum_Solution3( unsigned  int n)
{
     static fun f[ 2] = {Solution3_Teminator, Sum_Solution3};
     return n + f[!!n](n -  1);
}


int main()
{
    cout << Sum_Solution3( 100) << endl;
     return  0;
}
 
思路四:
    利用模版类型求解。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
#include <iostream>

using  namespace std;


template < unsigned  int n>
struct Sum_Solution4
{
     enum Value { N = Sum_Solution4 < n -  1 >::N + n};
};

template <>  struct Sum_Solution4< 1>
{
     enum Value { N =  1};
};

template <>  struct Sum_Solution4< 0>
{
     enum Value { N =  0};
};


int main()
{
    cout << Sum_Solution4< 100>::N << endl;
     return  0;
}

转载于:https://www.cnblogs.com/codemylife/p/3767128.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值