Tuesday, 1 October 2019

Palindrome Program in Java

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?

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
checkPalindrom(sc.nextLine());
}
private static void checkPalindrom(String nextLine) {
System.out.println("check for strign to be palindrop or not!!       "+nextLine);
String reversStr=reverseStr(nextLine);
System.out.println("reverse string is "+reversStr);
if(reversStr.equals(nextLine))
System.out.println("palindrom!!");
else
System.out.println("not palindrom!!");
}
public static String reverseStr(String str) {
if(str==null|| str.isEmpty())
return str;
return str.charAt(str.length()-1)+reverseStr(str.substring(0,str.length()-1));
}

}




No comments:

Post a Comment

Note: only a member of this blog may post a comment.