Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Recursive function for inverting an int

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?

like image 897
JorgeeFG Avatar asked May 24 '26 00:05

JorgeeFG


2 Answers

int invertint( int num ) {
  int i ;

  for(i=10;num/i;i*=10);
  i/=10;
  if(i == 1) return num;
  return( (num % 10) * i + invertint( num / 10 ) );
}
like image 128
BLUEPIXY Avatar answered May 26 '26 14:05

BLUEPIXY


Your mistake is that in the last statement you are multiplying rest by 10. Why only 10? You need to shift the rest digit by as many digits as there are left in the remaining part of the number. You are shifting by only 1. No wonder it works only for 2-digit numbers.

The last part should be done along the lines of

int tail = invert( div );
int deg = /* number of digits in `tail` */;
return rest * (int) pow(10, deg) + div;
like image 22
AnT Avatar answered May 26 '26 15:05

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!