0

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.

2
  • 1
    sorry the question needs reformatting, my code did not show properly, I will fix that Commented Dec 18, 2013 at 23:14
  • You're over complicating this. I don't see any reason why you'd need to make a recursive call in an if. It may work but is definitely hard to follow and, looks like, subject to mistakes. Commented Dec 18, 2013 at 23:22

5 Answers 5

6

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
Sign up to request clarification or add additional context in comments.

Comments

5

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.

6 Comments

when given input of 843 it returned 78, so it is not working as planned
Thanks, works fine, sorry for the delay, I was eaating.
Math.pow is very expensive. You don't need something that complicated, see my answer.
I see, both methods work well, however for sake of ease I will just go with the one above, as I currently am not to worried about memory, as my program simply does that and a Fibonacci sequence, but thanks for your advice, I will take that into account in the future
@PeterLawrey, sure, thanks for pointing that out. Hovewer, this assignment is clearly not aimed at efficiency, that's the reason why I'd proposed a solution that uses algorithm which is a bit easier to understand.
|
3

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.

3 Comments

yeah no loops are allowed, and we have not used logarithms in the course at all so I dont believe that is what the teacher wants.
@abysmaldan: If you can't use Java's Math.log10, write your own and call it from RevDigs it's pretty straight forward. It will require loops but I doubt that would matter since it's not directly in the recursion.
If you can't use loops at all, you could write a separate recursive routine to count the number of digits! if n < 10 return 1 else return 1 + numberOfDigits(n/10).
0
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));
    }

}

1 Comment

Please elaborate and explain your suggestions.
0

Try this:

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;
        }
    }

1 Comment

Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. Please edit your answer to include clarification, context and try to mention any limitations, assumptions or simplifications in your answer.

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.