Reverse a number using recursion

Problem: Print reverse of a number in Java using recursion

We will use simple recursion to print reverse of a number. In each call we will print number % 10 and divide number by 10 for next call.
This code will work for positive numbers.

public class ReverseNumber {

	public static void main(String[] args) {
		int num = 655664655;
		System.out.println(num % 10);
		reverseNumber(num);
	}

	private static void reverseNumber(int num) {
		if (num == 0)
			return;
		System.out.print(num % 10);
		reverseNumber(num / 10);
	}

}

Here we are printing num % 10 in every call.

I hope this is simple way to print reverse. Please comment for any questions or suggestions.

Leave a Reply