Palindrome Program in Java
case 1 : write a program to check whether a number is palindrome or not?
logic::
sum= sum*10+r
Example -12345
r=5
sum=0*10+5=5
number=1234
r=4
sum=5*10+4=54
number =123
r=3
sum=54*10+3=543
number=12
r=2
sum=543*10+2=5432
number =1
r=1
sum=sum*10+r
=5432*10+1=54321
code::::
private static void method2() {
/*
*
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"
*/
int r,sum=0,temp;
int n=434;
temp=n;
while(n>0){
r=n%10;//reminder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
{
System.out.println("number is palindrom");
}
else{
System.out.println("number is not a palindrom");
}
}
in below code method2(); is used to check the given number is palindrome or not
case 2: write a program to check whether given string is palindrome or not?
No comments:
Post a Comment
Note: only a member of this blog may post a comment.