Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

java - Using Recursion to reverse an integer without the use of strings

I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.

My first attempt:

/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
    int reverse = 0;
    if(input == 0)
    {
        return reverse;
    }
    int tempRev = RevDigs(input/10);
    if(tempRev >= 10)
        reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
    if(tempRev <10 && tempRev >0)
        reverse = input%10*10 + tempRev;
    if(tempRev == 0)
        reverse = input%10;   
    return reverse;
}//======================

I also tried to use this, but it seems to mess up middle digits:

/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
    int reverse = 0;
    if(input == 0)
    {
        return reverse;
    }
    if(RevDigs(input/10) == 0)
        reverse = input % 10;
    else
    {
        if(RevDigs(input/10) < 10)
            reverse = (input % 10) *10 + RevDigs(input/10);
        else
            reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
        }
    return reverse;
}

I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about using two methods

public static long reverse(long n) {
    return reverse(n, 0);
}

private static long reverse(long n, long m) {
    return n == 0 ? m : reverse(n / 10, m * 10 +  n % 10);
}

public static void main(String... ignored) {
    System.out.println(reverse(123456789));
}

prints

987654321

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...