Define a class to accept a number from user and check if it is an EvenPal number or not. (The number is said to be EvenPal number when the number is a palindrome number — a number is palindrome if it is equal to its reverse — and the sum of its digits is an even number.) Example: 121 is a palindrome number Sum of the digits = 1 + 2 + 1 = 4, which is an even number
Topic: Digit extraction — EvenPal number
Answer
import java.util.Scanner;
class EvenPal { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a positive number : "); int n = sc.nextInt();
int num = n, d, rev = 0, sum = 0;
while(num > 0) { d = num % 10; rev = rev * 10 + d; sum = sum + d; num = num / 10; }
if(rev == n && sum % 2 == 0) System.out.println("It is an EvenPal number " + n); else System.out.println("It is not an EvenPal number"); } }
Two conditions must both hold, so a single loop gathers both facts and one if with && tests them.
The reversing line is the one to memorise: rev = rev * 10 + d. Each time round, the digits already collected shift one place left and the new digit drops into the units place. For 121: rev goes 1, then 12, then 121.
The digit sum is gathered in the same pass — there is no need for a second loop.
Keeping the original in n is essential, because the loop destroys num and you must compare the reverse against the ORIGINAL number. This is the commonest mistake in palindrome questions: looping on n itself leaves nothing to compare with.
Trace 121: rev = 121 equals n, and sum = 4 is even, so it is EvenPal. Trace 123: rev = 321 does not equal 123, so it fails at the first test — both samples match the paper.
n int - the number entered by the user (kept unchanged) num int - working copy of n, reduced digit by digit d int - the digit currently extracted rev int - the number built up in reverse sum int - running total of the digits sc Scanner - object used to read input