-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCourse3_week2_codes.cpp
113 lines (84 loc) · 1.66 KB
/
Course3_week2_codes.cpp
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
Exercise-1
int RecursiveSum(int n) {
if (n == 0) {
return 0;
}
else {
return n + RecursiveSum(n - 1);
}
}
=======================
Exercise-2
int ListSum(vector<int> nums) {
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
}
return sum;
}
or
int ListSum(vector<int>& nums) {
if (nums.size() == 1) {
return nums.at(0);
}
else {
vector<int> new_vector(nums.begin() + 1, nums.begin() + nums.size());
return nums.at(0) + ListSum(new_vector);
}
}
========================
Exercise-3
int BunnyEars(int n) {
if (n == 0) {
return 0;
}
else {
return 2 + BunnyEars(n - 1);
}
}
=========================
Exercise-4
std::string ReverseString(std::string str) {
int n = str.length();
// Swap character from start to end until midpoint
for (int i = 0; i < n / 2; i++) {
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
}
return str;
}
or
string ReverseString(string s) {
if (s.length() == 1) {
return s;
}
else {
return s.substr(s.length() - 1) + ReverseString(s.substr(0, s.length() - 1));
}
}
============================
Exercise-5
int GetMax(const vector<int>& nums) {
if(nums.empty()) {
// Handle the case where the vector is empty.
return 0;
}
int max_value = nums[0];
for(int i = 1; i < nums.size(); i++) {
if(nums[i] > max_value) {
max_value = nums[i];
}
}
return max_value;
}
or
int GetMax(vector<int>& nums) {
if (nums.size() == 1) {
return nums.at(0);
}
else {
vector<int> new_vector(nums.begin() + 1, nums.begin() + nums.size());
return max(nums.at(0), GetMax(new_vector));
}
}