‹ Back to the paper
A class Palin has been defined to check whether a positive number is a Palindrome number or not…
A class Palin has been defined to check whether a positive number is a Palindrome number or not.
The number ‘N’ is palindrome if the original number and its reverse are same.
Some of the members of the class are given below:
Class name : Palin
Data members/instance variables:
num : integer to store the number
revnum : integer to store the reverse of the number
Methods/Member functions:
Palin( ) : constructor to initialize data members with legal initial values
void accept( ) : to accept the number
int reverse(int y) : reverses the parameterized argument ‘y’ and stores it in ‘revnum’ using recursive technique
void check( ) : checks whether the number is a Palindrome by invoking the function reverse( ) and display the result with an appropriate message
Specify the class Palin giving the details of the constructor( ), void accept( ), int reverse( int ) and void check( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Answer
Answer
AIimport java.util.Scanner;
class Palin
{
int num; // number to be checked
int revnum; // reverse of the number
Palin()
{
num = 0;
revnum = 0;
}
void accept()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive number: ");
num = sc.nextInt();
}
// reverses y recursively and stores the result in revnum
int reverse(int y)
{
if (y == 0)
return revnum;
revnum = revnum * 10 + y % 10;
return reverse(y / 10);
}
void check()
{
revnum = 0;
reverse(num);
if (num == revnum)
System.out.println(num + " is a Palindrome number");
else
System.out.println(num + " is not a Palindrome number");
}
public static void main(String args[])
{
Palin obj = new Palin();
obj.accept();
obj.check();
}
}Explanation: the constructor sets num and revnum to 0. reverse(y) takes the last digit of y (y % 10), appends it to revnum (revnum * 10 + digit) and calls itself with y / 10 until y becomes 0, when it returns revnum. check() resets revnum, calls reverse(num) and compares num with revnum. Tested by running: input 12321 printed "12321 is a Palindrome number".From ISC 2017 Computer Science Paper 1, question 7.