In: Computer Science
java
Write a recursive program to reverse a positive integer. . Your method should take a non negative integer as a parameter and return the reverse of the number as an integer. e.g. if you pass 12345, your method should return 54321.
THE PROGRAM ASKS TO RETURN THE REVERSE OF A NON NEGATIVE NUMBER.
Examples :
Input : num = 12345 Output : 54321 Input : num = 876 Output : 678
HERE IS A FLOWCHART DEPICTING TO FIND THE REVERSE OF THE NUMBER ---
HERE IS THE CODE I HAVE WRITTEN ON MY TERMINAL FOR REVERSING THE NUMBER ,THEN AFTER I HAVE PROVIDED WITH THE CODE AND THE OUTPUT AS IT IS :
Example:
num = 4562
rev_num = 0
rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456
rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45
rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4
rev_num = rev_num *10 + num%10 = 265 + 4 = 2654
num = num/10 = 0
// Java program to reverse a number
// Java program to reverse digits of a number
// Recursive function to
// reverse digits of num
public class REVERSE_NUMBER
{
static int rev_num = 0;
static int base_pos = 1;
static int reversDigits(int num)
{
if(num > 0)
{
reversDigits(num / 10);
rev_num += (num % 10) *
base_pos;
base_pos *= 10;
}
return rev_num;
}
public static void main (String[] args)
{
int test;
Scanner sc= new
Scanner(System.in);
System.out.println("Enter the
number of times you want to test the code");
test= sc.nextInt();
for(int i=1;i<=test;i++)
{
int num =sc.nextInt(); ;
System.out.println("Reverse of no.
is "
+
reversDigits(num));
}
}
OUTPUT AS IT APPRES ON MY SYSTEM:--
THANKs