简体   繁体   中英

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.

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

What about:

public int RevDigs(int input) {
    if(input < 10) {
        return input;
    }
    else {
        return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
        /* here we:
           - take last digit of input
           - multiply by an adequate power of ten
             (to set this digit in a "right place" of result)
           - add input without last digit, reversed
        */
    }
}

This assumes input >= 0 , of course.

The key to using recursion is to notice that the problem you're trying to solve contains a smaller instance of the same problem. Here, if you're trying to reverse the number 13579, you might notice that you can make it a smaller problem by reversing 3579 (the same problem but smaller), multiplying the result by 10, and adding 1 (the digit you took off). Or you could reverse the number 1357 (recursively), giving 7531, then add 9 * (some power of 10) to the result. The first tricky thing is that you have to know when to stop (when you have a 1-digit number). The second thing is that for this problem, you'll have to figure out how many digits the number is so that you can get the power of 10 right. You could use Math.log10 , or you could use a loop where you start with 1 and multiply by 10 until it's greater than your number.

package Test;

public class Recursive {
    int i=1;
    int multiple=10;
    int reqnum=0;
    public int recur(int no){
        int reminder, revno;

        if (no/10==0) {reqnum=no;
        System.out.println(" reqnum "+reqnum);
        return reqnum;}
        reminder=no%10;
        //multiple =multiple * 10;
        System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
        i++;

        no=recur(no/10);
        reqnum=reqnum+(reminder*multiple);
        multiple =multiple * 10;
        System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
        return reqnum;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int num=123456789;

        Recursive r= new Recursive();
        System.out.println(r.recur(num));
    }

}
import java.io.*;

public class ReversalOfNumber {
    public static int sum =0;
    public static void main(String args []) throws IOException
    {
        System.out.println("Enter a number to get Reverse & Press Enter Button");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String input = reader.readLine();
        int number = Integer.parseInt(input);
        int revNumber = reverse(number);
        System.out.println("Reverse of "+number+" is: "+revNumber);
    }
    public static int reverse(int n)
    {       
        int unit;
        if (n>0)
        {
            unit = n % 10;
            sum= (sum*10)+unit;
            n=n/10;
            reverse(n);
        }
        return sum;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM