2

I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.

This is what I have so far:

public class PrintDigits {

    public static void main(String[] args) {
        System.out.println("Reverse of no. is " + reversDigits(91));
    }

    /* Recursive function to reverse digits of num */
    public static int reversDigits(int number) {
        if (number == 0)
            return number;
        else {
            return number % 10;
        }
    }
}

I feel like there is only one line of code that I am missing, but not sure what I need to do to fix it.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
As Sa
  • 31
  • 1
  • 1
  • 3

15 Answers15

8
public static void main(String[] args) {
    reverseDigits(98198187);
}

/* Recursive function to reverse digits of num */
public static void reverseDigits(long number) {
    if (number < 10) {
        System.out.println(number);
        return;
    }
    else {
        System.out.println(number % 10);
        reverseDigits(number/10);
    }
}
renz
  • 1,072
  • 3
  • 11
  • 21
3

This doesn't exactly answer the question, but it actually computes the entire reversed number instead of printing the digits as they are calculated. The result is an int with the digits in reversed order. Much more powerful than printing out the string version of the numbers one by one:

public class Reverse {
    public static void main(String[] args) {
        // input int parameter
        int param = Integer.parseInt(args[0]);
        System.out.println(reverse(param)); 
    }

    public static int reverse(int input) {
        return reverse(input, 0); 
    }

    private static int reverse(int original, int reversed) {
        // get the rightmost original digit and remove it
        int rightmost = original % 10;
        original -= rightmost;
        original /= 10;

        // add rightmost original digit to left of reversed
        reversed += rightmost * Math.pow(10, numDigits(original));

        return (original == 0)
            ? reversed
            : reverse(original, reversed);
    }

    public static int numDigits(int number) {
        number = Math.abs(number);

        if (number >= 10) {
            return 1 + numDigits(number /= 10);
        } else if (number > 0) {
            return 1;
        } else {
            return 0;
        }
    }
}
rickcnagy
  • 1,774
  • 18
  • 24
  • I do like the idea of creating the reversed number. However, you can ditch numDigits and increase the number by multiplying itself by 10 and adding the new digit. reversed = 10*reversed + rightmost; – ofer.sheffer May 10 '14 at 23:34
3
public static void reversDigits(long number) {
    System.out.println(number % 10);
    if (number >= 10) {
        reversDigits(number / 10);
    }
}

This is shortest/simplest version so far;)

  • 1
    This code is incorrect, for example the test case 10 would only display the number 0. – Andres S Apr 20 '16 at 22:54
  • I'm so sorry. You are right. The idea is to print last digit of the number and then if it has higher place value than ones perform a recursive call. I just made a small logic mistake, so usual :) – Edmund Stanishevski Apr 23 '16 at 20:33
2
public static int reversDigits(int num) {
    if(num < 1) {
        return 0;
    }

    int temp = num % 10;
    num = (num - temp)/10;
    System.out.println(temp);

    return reversDigits(num);
}

This will print the digits one at a time in reverse order. You don't need to do System.out in your main method.

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
Vineet Singla
  • 1,609
  • 2
  • 20
  • 34
1

I found I had to pick off the highest digit (on the left) and work towards the rightmost digit. I couldn't get a recursive one to work going from right to left.

public static int reverseItRecursive(int number)
{
    if (number == 0)
        return 0;

    int n = number;
    int pow = 1;

    while (n >= 10)
    {
        n = n / 10;
        pow = pow * 10;
    }
    return (n + reverseItRecursive(number - n*pow)*10);
}
PHSTeach
  • 51
  • 3
1

This should work

 int rev = 0;
 int reverse(int num)
{
    if (num < 10) {
        rev = rev*10 + num;
    }
    else {
        rev = rev*10 + (num % 10);
       num = reverse(num / 10);

    }
    return rev;
}
Seid.M
  • 185
  • 7
1
//Try out this, recursion with singe variable using Math class.
public static void main(String[] args) {
    // Let the number be 139
    int n=139;
    System.out.println("reverse is "+rev(n));
}
static int rev(int n){
    if (n==0)return 0;
    else {
        return n%10*(int) Math.pow(10,(double) (int)Math.log10(n))+rev(n/10);
    }    
}
1

This method reverse the integer and returns the result without using any string functions, Math, or by just printing

public class ReverseNumber {

    public static void main (String[] args) {
        ReverseNumber rNumber = new ReverseNumber();
        System.out.println(rNumber.reverseRecursive(1234,0)); // pass zero to initialize the reverse number
    }
    public int reverseRecursive(int n, int reverse) {// n - the number to reverse
        // System.out.println(n);

        if (n != 0){
            reverse = reverse * 10;
            reverse = reverse + n %10;
            n = n/10;
        } else {
              return reverse;
        }
    return reverseRecursive(n,reverse);
}}
user2001627
  • 257
  • 2
  • 16
1
 public void reverse(int num){
        System.out.print(num %10);
        if(num / 10 == 0){
              return;
        }
        reverse(num /10);
         return;
    }
daniel gi
  • 396
  • 1
  • 7
  • 19
1

This is very shortest/simplest way in two lines code:

    public static int reverseNumber(int n) 
    {
        System.out.println(n % 10);
        return (n/10 > 0) ? reverseNumber(n/10) : n;
    }
venkat
  • 5,648
  • 16
  • 58
  • 83
0

I came looking for a more elegant version than mine, but perhaps this just requires a bit of a messy algorithm. Mine also returns the actual integer value which I agree is much more useful than only printing the string: Mine:

public static int reverse(int n){
        if(n<10)return n;
        return  n%10*(int)Math.pow(10,(int)Math.log10((double)n)) + reverse(n/10);
    } 

so this returns the last digit, multiplied by 10^current power + (recursive call)

Robert
  • 1
0

Here you go :

static String reverseDigits(int n)
{
    String N = "";
   if ( n== 0)
       return N;
   else
   {
       N += n%10;
       return N + reverseDigits(n/= 10);
   }            
}

This is of course returned as String.

If you want it as int all you have to do is parse it using Integer.parseInt()

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
juniorcoder
  • 25
  • 2
  • 8
0
//Reverse a number using recursion by bibhu.rank
public class Rev_num {
    public static int revnum(int x){
        int temp1=x,temp2=1;
        if(x<10){
            return x;
        }
        while(temp1>=10){
            temp2*=10;
            temp1/=10;
        }
        if(((x%temp2) < (temp2/10))&& x%temp2!=0){
            int c=temp2;
            while(c> x%temp2){
                c/=10;
            }
            c=temp2/c;
            temp2=x%temp2;
            return((temp1)+(c*revnum(temp2)));
        }
        temp2=x%temp2;

        return (temp1+(10*revnum(temp2)));

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter a number");
        Scanner y=new Scanner(System.in);
        System.out.println(revnum(y.nextInt()));
        y.close();


    }

}
0
   public class reverseIntRec{
        public static void main(String args[]) {
            System.out.println(reverse(91));
        }
        public static int reverse(int x) {
         String strX = String.valueOf(x);
          if (Math.abs(x) < 10)
                return x;
          else 
            return x % 10 * ((int) Math.pow(10, strX.length()-1)) + reverse(x/10);
        }
    }

Here is my answer return as integer. I converted x into string to see how many 0s you should multiply with.

For example: reverse(91) returns 1 * 10 + reverse (9), and that returns 10 + 9 = 19.

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

Relatively simple since you need to print one digit per line. You also state that you print its digits, which implies that leading zeros are still going to be displayed. Our test case

123000 prints :

0

0

0

3

2

1

here is the code, no while, no string, and no math library :

    private void printIntegerDigitsReversed(int i) {
        if (i / 10== 0 ){
            System.out.println(i);
        }
        else{
            printIntegerDigitsReversed(i%10);
            printIntegerDigitsReversed(i/10);
        }
    }