Results 1 to 7 of 7

Thread: [Resolved] Recursion: Reverse an Integer

  1. #1

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    [Resolved] Recursion: Reverse an Integer

    I need to write a recursive function to reverse the order of digits in an integer. This is a homework problem, so it has to be done using recursion (not a loop or anything). This is what I've come up with so far:

    Code:
    public int revDigits (int num) { 
      if (num < 10) {
          return num;
      } else {
          int s = num / 10;
          int d = num % 10;
    
          int i = revDigits(s);
    
          return (d * 10) + i; // incorrect
    
          // need to find out how many digits in d:
          //return (d * 10^(num digits in d)) + i);
      }
    }
    The problem that I've come across is commetted at the bottom. Any help with solving this would be appreciated. Thanks in advance.
    Last edited by The Hobo; Nov 21st, 2004 at 10:31 PM.
    My evil laugh has a squeak in it.

    kristopherwilson.com

  2. #2
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111
    here is how i reversed a string using substring() once. I don't know if this will help you or not. Maybe you can get an idea though.

    Code:
    public class ReverseString
    {
     public String reverse(String arg)
     {
    	String tmp = null;
    	if (arg.length() == 1)
    	{
    		return arg;
    	}
    	
    	else
    	{
    		
    
    		String lastChar = arg.substring(arg.length()-1,arg.length());
    		
    		String remainingString = arg.substring(0, arg.length() -1);
    
    		tmp = lastChar + reverse(remainingString);
    		return tmp;
    		
    		
    	}
      }
    }

    Code:
    import java.io.*;
    
    
    public class TestReverse
    {
    	public static void main(String[] args) throws IOException
     	{
    		System.out.println("Enter a line to be reversed");
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		String inData;
    		inData = br.readLine();
    		ReverseString rs = new ReverseString();
    		System.out.println("Reversed: " + rs.reverse(inData));	
    	}
    }

  3. #3

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256
    Thanks, but I have the logical of how to do it down, I've just run into a specific problem. See the commented out portion of my code. What I need, unless there is a better way to go about this, is a way to count the number of digits in a number (hopefully without writing another method).
    My evil laugh has a squeak in it.

    kristopherwilson.com

  4. #4
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111
    This is the best I could do. I know it's not the same method, but maybe you can use it.

    Code:
    public int reverseDigits(int num)
     {
    	int newInt = 0;
    	int tmpInt = num;
    	while(tmpInt != 0)
     	{
    		newInt *= 10;
    		newInt += tmpInt % 10;
    		tmpInt /= 10;
    	}
    	return newInt;
     }

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    A problem that is particularly unsuited for recursion...

    Anyway.

    Since I just wrote a good deal of code and then had to delete it because it wouldn't work, let's try another way. What you need is a depth tracker.
    Code:
    int reverseDigits(int i) {
      return revDigsRecur(i, new IntWrap());
    }
    
    int revDigsRecur(int i, IntWrap tracker) {
      if(i < 10) {
        ++tracker.i;
        return i;
      } else {
        int rev = revDigsRecur(i / 10, tracker);
        rev += (i % 10) * Math.pow(10, tracker.i);
        ++tracker.i;
        return rev;
      }
    }
    
    class IntWrap {
      public int i = 0;
    }
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  6. #6

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256
    System_Error, I came up with something similiar to yours, I think:

    Code:
        public int revDigits (int num) { 
            if (num < 10) {
                return num;
            } else {
                int lastDigit = num % 10;
                int revSeq = revDigits(num / 10);
    
                // Following code counts digits in lastDigit
                int j = revSeq;
                int c = 0;
                while (j != 0) {
                    j = j / 10;
                    c++;
                }
    
                return (lastDigit * (int)Math.pow(10, c)) + revSeq;
            }
        }
    I know it's probably not best, but oh well.

    CB, all of the recursion problems he gave us are better to accomplish without recursion.

    Thanks for your help, guys.
    My evil laugh has a squeak in it.

    kristopherwilson.com

  7. #7
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Remember that your solution is O(n²), mine is O(n)...
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width