c - Not understand this recursive function that inverts digits of a number -


i found 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 set out analyzing it, have 1 doubt following, return starting point values obtained (num % 10) according understanding should (1,2,3,4,5) when trying calculation manually not expected value.

what happens here, if explains me this, or missed out something?

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, 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, end result is:

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

it simple math, non trivial rule (int)log10(num), explained @questionc in comment.


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Website Login Issue developed in magento -

Can the constants be defined inside a model file of a framework in PHP? -