Reverse Number ISC Computer Science 2022 Semester 2 Theory
Design a class Revno which reverses an integer number.
Example: 94765 becomes 56749 on reversing the digits of the number.
Some of the members of the class are given below:
Class name: Revno
Data members/instance variables:
num: to store the integer number
Member functions/methods:
Revno(): default constructor
void inputNum(): to accept the number
int reverse(int n): returns the reverse of a number by using recursive technique
void display(): displays the original number along with its reverse by invoking the method reverse()
Specify the class Revno, giving details of the constructor, void inputNum(), int reverse(int) and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.
class Revno{
int num;
public Revno(){
num = 0;
}
public void inputNum(){
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
num = Integer.parseInt(in.nextLine());
}
public int reverse(int n){
if(n < 10)
return n;
int d = n % 10;
n /= 10;
int len = String.valueOf(n).length();
int p = (int)(Math.pow(10, len));
return d * p + reverse(n);
}
public void display(){
System.out.println("Number: " + num);
int rev = reverse(num);
System.out.println("Reverse: " + rev);
}
public static void main(String[] args){
Revno obj = new Revno();
obj.inputNum();
obj.display();
}
}
Comments
Post a Comment