Home > Blockchain >  Convert to a recursive function
Convert to a recursive function

Time:01-13

Describe a recursive function that determines the number of variables a sign in a non-zero array. I did it in a non-recursive one, but I need it in a recursive one.

int recur_change_sign(int* arr, int n) {
    int count = 0;
    for (int i = 0; i < n - 1; i  ) {
        if ((arr[i] < 0 && arr[i   1] >= 0) || (arr[i] >= 0 && arr[i   1] < 0)) {
            count  ;
        }
    }
    return count;
}

CodePudding user response:

You can implement it very easily like this:

int recur_change_sign(int* arr, int n) {
    if (n <= 1) return 0;
    return ((arr[0] < 0 && arr[1] >= 0) || (arr[0] >= 0 && arr[1] < 0))   recur_change_sign(arr   1, n - 1);
}

CodePudding user response:

It can also be realized by removing it from the tail.

int recur_change_sign(int* arr, int n) {
    if (n <= 1) return 0;
    return ((arr[n-2] < 0 && arr[n-1] >= 0) || (arr[n-2] >= 0 && arr[n-1] < 0))   recur_change_sign(arr, n - 1);
}
  • Related