Palindrome Program in Java
Palindrome number in java: A palindrome number is a number that is same after reverse. For example 545, 151, 34543, 343, 171, 48984 are the palindrome numbers. It can also be a string like LOL, MADAM etc.
Palindrome number algorithm
- Get the number to check for palindrome
- Hold the number in temporary variable
- Reverse the number
- Compare the temporary number with reversed number
- If both numbers are same, print "palindrome number"
- Else print "not palindrome number"
public class Palindrome {
public static void main(String[] args) {
int num = 121, reversedInteger = 0, remainder, originalInteger;
originalInteger = num;
// reversed integer is stored in variable
while( num != 0 )
{
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
num /= 10;
}
// palindrome if orignalInteger and reversedInteger are equal
if (originalInteger == reversedInteger)
System.out.println(originalInteger + " is a palindrome.");
else
System.out.println(originalInteger + " is not a palindrome.");
}
}
Example 2: Program to Check Palindrome using for loop
public class Palindrome {
public static void main(String[] args) {
int num = 11221, reversedInteger = 0, remainder, originalInteger;
originalInteger = num;
// reversed integer is stored in variable
for( ;num != 0; num /= 10 )
{
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
}
// palindrome if orignalInteger and reversedInteger are equal
if (originalInteger == reversedInteger)
System.out.println(originalInteger + " is a palindrome.");
else
System.out.println(originalInteger + " is not a palindrome.");
}
}
When you run the program, the output will be:
11221 is not a palindrome.
0 comments:
Post a Comment