Reverse the digits: Asha’s birthday is shortly coming and her parents have planned to arrange for a house party. Deepa was Asha’s best friend and was expecting her birthday since a month. This is because Deepa’s Dad has promised her that he and Deepa together would design a Reverse Talking kitty toy all by themselves and gift it to Asha. Deepa believed that Asha might be overjoyed with this gift from her dear friend.
Deepa’s Dad put the best of his efforts to design the toy. As a first module in the design he intended to reverse a numeric input given to it. He needs your help to write a recursive method for reversing the digits of the given number N. Please assist him in the task.
Hence create a class named ReverseNumber with the following method.
Method Name | Description |
int reverse(int) | This recursive method should return the reverse of a N digit number. |
Create a driver class called Main. In the Main method, obtain input from the user in the console and display the reverse of a N digit number by calling the reverse method present in the ReverseNumber class.
[Note: Strictly adhere to the Object Oriented Specifications given in the problem statement.
All class names, attribute names and method names should be the same as specified in the problem statement.]
Input Format:
The first line of the input is an integer N.
Output Format:
Print the reverse of a N digit number.
Refer sample input and output for formatting specifications.
Sample Input 1:
1234
Sample Output 1:
4321
Sample Input 2:
32333333
Sample Output 2:
33333323
Solution
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int result = reverse(a);
System.out.println(result);
}
public static int reverse (int num)
{
if (num < 10)
{
return num;
}
else
{
int x = num % 10;
int y =reverse(num/10);
int d =(String.valueOf(y)).length();
x=x*(int)(Math.pow(10,d));
return x+y;
}
}
}
Happy Learning – If you require any further information, feel free to contact me.
Could you please explain the flow of the program..
Sure here is the flow of the program:
1. First we take the input from the user and store it in a variable named a.
2. Then we call the reverse function and pass the value of a as the argument.
3. In the reverse function we check if the number is less than 10, if it is then we return the number.
4. If the number is not less than 10 then we take the last digit of the number and store it in a variable named x.
5. Then we call the reverse function again and pass the number without the last digit as the argument.
6. Then we store the value returned by the reverse function in a variable named y.
7. Then we find the length of the number stored in y and store it in a variable named d.
8. Then we multiply the last digit of the number with 10 raised to the power of d.
9. Then we return the sum of x and y.