Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <vector>
- using namespace std;
- /**
- Given a vector of integers, the altSum method
- should return the alternating sum
- v[0] - v[1] + v[2] - v[3] + ...
- If the vector is empty, the alternating sum is zero.
- Use a recursive helper method. Do not use loops.
- */
- int altSumHelper(const vector<int>& values, int i)
- {
- int size = values.size();
- if (size == 0) {
- return i;
- }
- if (size % 2 == 0) {
- i -= values.back();
- } else {
- i += values.back();
- }
- vector<int> temp = values;
- temp.pop_back();
- return (altSumHelper(temp, i));
- }
- int altSum(vector<int> v)
- {
- return altSumHelper(v, 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement