简体   繁体   中英

Reversing digit using recursive function in C

I'm trying to create a recursive function to reverse digits of a number in C. This is what I've written. It works fine when used one time but when used multiple times it keeps piling the numbers together. I think the problem can be sorted if the sum is initialized to zero each time the function is called but I'm unable to do it. I've tried declaring sum=0 as a global variable but the result was the same. Input- 12 23 34 45 Output 21 2132 213243 21324354

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int digit_reverse(int N)
{
int rem;
static int sum=0;
  if(N>0)
  {
      rem=N%10;
      sum=sum*10+rem;
      digit_reverse(N/10);
  }
  else
  return 0;
  return sum;
 }

 int main()
 {
 int a[25],i;

 for(i=0;i<4;i++)
 {
     scanf("%d", &a[i]);
 }
 printf("Output\n");
 for(i=0;i<4;i++)
 {
    printf("%d\n",digit_reverse(a[i]));
 }

 }

Maybe you can write your function without using static variables:


void _digit_reverse(int N, int *sum)
{
    int rem;
    if (N > 0)
    {
        rem = N % 10;
        *sum = *sum * 10 + rem;
        _digit_reverse(N / 10, sum);
    }
}

int digit_reverse(int N)
{
    int sum = 0;
    _digit_reverse(N, &sum);
    return sum;
}

Or take the sum outside:


int sum = 0;

int digit_reverse(int N)
{
    int rem;
    if (N > 0)
    {
        rem = N % 10;
        sum = sum * 10 + rem;
        digit_reverse(N / 10);
    }
    else
        return 0;
    return sum;
}

int main()
{
    int a[25], i;

    for (i = 0; i < 4; i++)
    {
        scanf("%d", &a[i]);
    }
    printf("Output\n");
    for (i = 0; i < 4; i++)
    {
        sum = 0;
        printf("%d\n", digit_reverse(a[i]));
    }
}

I believe that the static variable gets initialized only once. This is the problem with your approach.

dude everything looks fine to me if the code do not needs to be reusable I can think of several solutions but keep in mind static and or global variables are not best practices unless necessarily required to. secondly change your

// from static int sum = 0;
// to
static long sum = 0;
// or 
static long long sum = 0;

the reason for this error is value overflow an integer cannot have more than 4 bytes of data in this specific case you definitly needs more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM