C: Recursive function for inverting an int
Posted
by
Jorge
on Stack Overflow
See other posts from Stack Overflow
or by Jorge
Published on 2012-07-05T14:57:10Z
Indexed on
2012/07/05
15:15 UTC
Read the original article
Hit count: 185
I had this problem on an exam yesterday. I couldn't resolve it so you can imagine the result...
Make a recursive function: int invertint( int num) that will receive an integer and return it but inverted, example: 321 would return as 123
I wrote this:
int invertint( int num ) {
int rest = num % 10;
int div = num / 10;
if( div == 0 ) {
return( rest );
}
return( rest * 10 + invert( div ) )
}
Worked for 2 digits numbers but not for 3 digits or more. Since 321 would return 1 * 10 + 23 in the last stage.
Thanks a lot!
PS: Is there a way to understand these kind of recursion problems in a faster manner or it's up to imagination of one self?
© Stack Overflow or respective owner