-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathaccumulate.cpp
More file actions
118 lines (104 loc) · 2.4 KB
/
accumulate.cpp
File metadata and controls
118 lines (104 loc) · 2.4 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
* Copyright(c) 2019 Jiau Zhang
* For more information see <https://github.com/JiauZhang/algorithms>
*
* This repo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation
*
* It is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with THIS repo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <list>
using namespace std;
/************************* soulution-1 **************************/
class add {
public:
add() { sum = sum + n; n++; }
//a static data member that can only be initialized at its definition
static int sum;
static int n;
static int getSum() { return sum; }
};
int add::sum = 0;
int add::n = 1;
int accumulate_1(int n)
{
add *sum = new add[n];
delete[] sum;
sum = NULL;
return add::getSum();
}
/************************* soulution-2 **************************/
class End;
End *end_start[2];
class End {
public:
virtual int sum(int n) {
return 0;
}
};
class Start: public End {
virtual int sum(int n) {
// n 非零时执行当前函数递归,
// 为零时实行父类函数,其直接返回,扮演终止条件
return end_start[!!n]->sum(n-1) + n;
}
};
int accumulate_2(int n)
{
if (n<1)
return -1;
End e;
Start s;
end_start[0] = &e;
end_start[1] = &s;
return end_start[!!n]->sum(n);
}
/************************* soulution-3 **************************/
typedef int (*func)(int n);
int Stop(int n)
{
return 0;
}
int Begin(int n)
{
static func f[2] = {Stop, Begin};
return f[!!n](n-1) + n;
}
int accumulate_3(int n)
{
return Begin(n);
}
/************************* soulution-4 **************************/
template <int n>
struct solution4 {
enum Value {
sum = solution4<n-1>::sum + n
};
};
template <>
struct solution4<1> {
enum Value {
sum = 1
};
};
int accumulate_4(int n)
{
const int m = 10;
struct solution4<m> s;
return s.sum;
}
int main(int argc, char **argv)
{
cout << accumulate_1(10) << endl;
cout << accumulate_2(10) << endl;
cout << accumulate_3(10) << endl;
cout << accumulate_4(10) << endl;
}