Kevin
Kevin

Reputation: 1151

Not understand this recursive function that inverts digits of a number

I found this code

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

int rev(int num)
{
    if(num < 10)
        return num;
    else
        return (num % 10) * pow(10, (int)log10(num)) + rev(num/10);
}

int main(void)
{
    printf("%d\n", rev(12345));

    return 0;
}

And I set out to analyzing it, but now I have one doubt it is the following, to return to the starting point what values are obtained with (num % 10) according to my understanding should be (1,2,3,4,5) but when trying do the calculation manually I do not get the expected value.

What happens here, if someone explains to me this, or I missed out something?

Upvotes: 0

Views: 67

Answers (1)

Jonatan Goebel
Jonatan Goebel

Reputation: 1139

int rev(int num) // num = 12345
{
    if(num < 10) // false
        return num;
    else
        return (num % 10) * pow(10, (int)log10(num)) + rev(num/10);
        //     (12345 % 10) * 10 ^ (log 12345) + rev(12345/10);
        //     5 * 10 ^ (4) + rev (1234)
        //     50000 + rev(1234)
}

Based on this, we can assume that:

rev(12345) = 50000 + rev(1234)
rev(1234) = 4000 + rev(123)
rev(123) = 300 + rev(12)
rev(12) = 20 + rev(1)
rev(1) = 1

So, the end result is:

rev(12345) = 50000 + 4000 + 300 + 20 + 1 = 54321

It is a simple math, the only non trivial rule is (int)log10(num), but it was explained by @QuestionC in his comment.

Upvotes: 4

Related Questions