Recursion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • quakersquares
    New Member
    • Oct 2006
    • 7

    Recursion

    I can get any number to work as long as it doesnt include a 0. If it has a 0 the reversed number just comes out with the 0 on the end. I cannot figure out why. I think may have just made it too complicated and need to redo it. But if someone can help me I would appreciate it

    [CODE=cpp]
    int reverseDigit(in t a)
    //reverseDigit reverses the order of the digits in an integer. So 1234 becomes 4321
    //It only has to be passed the integer, and it returns its reversed order
    {
    int x = 1; //for while loop
    if(a < 10) return a;
    else
    {
    int b = (a%10)*10;
    cout << b << endl;
    int c = reverseDigit(a/10);
    if(b==0) return (c*10);
    else if(c < 10) return (c+b);//if c is less than 10 it only needs to be added to b
    else //else we have to find how big b has to be for the next decimal point past c
    {
    while(x <= c) x = x*10;
    b = x*(a%10);
    return (b+c);
    }
    }
    }
    [/CODE]
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Your problem is this line

    [code=cpp] if(b==0) return (c*10);[/code]

    *10 puts the 0 in the wrong place, it adds it to the right hand end of the number where as you need to add the digits to the left hand end.

    However knowing that does help much, if you reverse 1203 using your function it will do this

    1. stick 3 on the left hand end of 120 reversed
    2. stick 0 on the left hand end of 12 reversed
    3. stick 2 on the left hand end of 1 reversed

    the value of step 3 is 21, however the value of step 2 is 021 but since leading 0 have no meaning in a binary number this is 21. Step 2 and 3 return the same value.


    This is quite a classic example, it is very complicated to write a function that reverse the digit recursively using the interface function protoype. Using a slightly altered prototype it is simple, I solved the problem using this function structure

    [code=cpp]
    static int rd_helper(int a, int ra)
    {
    <code snipped, after all you need something to do :D>
    }

    int reverseDigit(in t a)
    //reverseDigit reverses the order of the digits in an integer. So 1234 becomes 4321
    //It only has to be passed the integer, and it returns its reversed order
    {
    return rd_helper(a, 0);
    }
    [/code]

    Not the original function is used as an interface onto another, recursive function with a slightly different prototype. This passes extra data at each recursion, the user does not need to know about this data but doing it this way means that the function rd_helper only contains a handful of code lines (a recursion end statement, a calculation line and a call to itself).


    The recursion is simple using the right data but the interface function does not use all that data.

    Comment

    Working...