Search code examples
c++integeradditionnegative-integer

Why adding negative integers result in a positive integer on this C++ Program?


This program basically checks the two ends of a given interger sequence, adds the greatest of the two to R and changes the sign of the end we didn't choose. Repeats the process until there's only one number left (which is not add to R). The first line of the input specifies the quantity of intergers in the sequence and the others left is the sequence itself.

For example, if we input "5 5 4 3 2 1", we should get "14", because only the "1" doesn't get add to R.

For some reason when I input "5 -5 -4 -3 -2 -1" I'm getting an output of "10" instead of "-10".

#include <iostream>
using namespace std;

int main(void) {
    int N, *L, R = 0, i = 0, d = 0;
    cin >> N;
    L = new int[N];
    for (; i < N; ++i) cin >> L[i];
    i = 0;
    d = N - 1;
    while (d != i) {
        if (L[i] > L[d]){
            R += L[i];
            L[d] *= -1;
            ++i;
        }
        else {
            R += L[d];
            L[i] *= -1;
            --d;
        }
    }
    cout << R << endl;
    return 0;
}`

Solution

  • Let's look at what happens during the first two iterations. We start with:

    i = 0
    d = 4
    L = -5 -4 -3 -2 -1
    R = 0
    

    The greater element is L[d], so we add that, change the sign of L[i], and decrement d, so now we have:

    i = 0
    d = 3
    L = 5 -4 -3 -2 -1
    R = -1
    

    Now the greater element is L[i], so we add that, change the sign of L[d], and increment i. So now we have:

    i = 1
    d = 3
    L = 5 -4 -3 2 -1
    R = 4
    

    As you can see, after just two iterations the result is already positive, because we added 5 this time.

    And on all future iterations, we'll only add the numbers that have been made positive.