Daiana Stefanov
Daiana Stefanov

Reputation: 13

Recursive function for reversing a number

The statement of my problem is this:

Write a recursive function that takes a natural number as argument and returns the value of the number read backwards (with the decimal digits in opposite order):

E.g : f(3120) = 213

I have solved the problem but I used static to store my reversed number as in the code below:

unsigned long f(unsigned long n){
    static long rev;
    if(n==0)
        return 0;
    else            
        {
            rev=rev*10+n%10;
            f(n/10);
        }
    return rev;         
}

but I would like to know if there is a way to solve this problem without using the static data type and still keeping only one parameter in the function.

Upvotes: 0

Views: 420

Answers (2)

michael-tkach
michael-tkach

Reputation: 259

You could put current result as an argument of your function:

int f(int x, int r = 0)
{
    if (x == 0) return r;
    return f(x / 10, r * 10 + x % 10);
}

Upvotes: 1

CiaPan
CiaPan

Reputation: 9570

Of course. Just remove the word static from your code and do calulations in loop:

unsigned long f(unsigned long n){
    long rev = 0;
    while(n != 0) {
        rev = rev*10 + n%10;
        n /= 10;
    }
    return rev;
}

Upvotes: 2

Related Questions