0

I have this recursive function to reverse a positive integer. Anybody having an efficient algorithm to do the task using fewer recursive calls (but still using recursion), please post here!

int countDigit (const int & _X) {
    if (_X < 10)
        return 1;
    return (countDigit(_X / 10) + 1);
}

int getPower (const int & _X, const int & _Y) {
    if (_Y == 0)
       return 1;
    int ans = getPower(_X, _Y / 2);
    if (_Y % 2)
       return _X * ans * ans;
    return ans * ans;
 }

 int reverseDigit (const int & digit)  {
    if (digit < 10) {
      return digit;
    }
    int num = (digit % 10) * getPower(10, countDigit(digit / 10));
    return num + reverseDigit(digit / 10);
 }
1
  • 1
    Might have better luck on Code Review Commented Jun 16, 2015 at 1:20

2 Answers 2

1

Sure ... effectively read in digits from the number and add them to the end of a temporary number:

EDIT: Based on the questioner's bizarre modification of the question (to require recursion), I have edited my clean iterative solution to include an arbitrary amount of recursion, denoted by the positive integer [recurse].

int reverseDigit(int digit, int recurse=1) {
    if (recurse>0) reverseDigit(digit,recurse-1);

    int num=0;
    while (digit!=0) {
        num*=10;
        num+=digit%10;
        digit/=10;
    }
    return num;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think you can remove the line vector<int> foo;
I was actually asking for a recursive method not iterative.
@PakCoder you specifically asked to "avoid so much recursive calls" in your question. You'd be hard pressed to do better at meeting that goal than avoiding all of them.
Thanks @Steephen ... you are right. PakCoder ... I'm not sure what you want, given WhozCraig 's response.
0

This is recursive

void reverse(int number, int& result)
{
if (number == 0) return;
else
   {
    result *= 10;
    result += number % 10; 
    reverse(number / 10, result ); 
   }
}

This is how you call it with (545146548) example

   void main()
   {
       int result = 0;
       reverse(545146548, result);
       cout << result << endl;
   };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.