Java Program to Check Palindrome Number
class PalindromeNumber
{
public static void main(String[] args)
{
int num = 755, reversedNum = 0, remainder;
// store the number to originalNum
int originalNum = num;
// get the reverse of originalNum
// store it in variable
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// check if reversedNum and originalNum are equal
if (originalNum == reversedNum) {
System.out.println(originalNum + " is
Palindrome.");
}
else {
System.out.println(originalNum + " is not
Palindrome.");
}
}
}
Output :
755 is not a palindrome
Explanation :
1. Variable Initialization:
- num is initialized to the number 755, which is the number we want to check for palindromicity.
- reversedNum is initialized to 0, which will store the reverse of num.
- remainder is declared to store the remainder when num is divided by 10.
- originalNum is used to store the original value of num because we need it for comparison later.
- remainder is calculated by taking the remainder when num is divided by 10. This gives the last digit of num.
- reversedNum is updated by multiplying its current value by 10 and adding the remainder. This effectively reverses the digits of num.
- num is updated by integer division (num /= 10), removing the last digit.
After the loop, num becomes 0 because all its digits have been processed. Now, reversedNum holds the reverse of the original number.
4. Comparison: The program compares the originalNum (the original number) with reversedNum (the reverse of the original number).
4. Comparison: The program compares the originalNum (the original number) with reversedNum (the reverse of the original number).
- If they are equal, it means the original number is a palindrome, so it prints a message saying that the number is a palindrome.
- If they are not equal, it means the original number is not a palindrome, so it prints a message saying that the number is not a palindrome.
Comments
Post a Comment