Palindrome in Java Example
Palindrome:
Logic:
Given Number/String should be equal with the Reversed of the given Number/String.
Eg:
101 – Palindrome Number (Given and Reverse of the given is equal (101 and 101 only)).
100 – Not a Palindrome Number (Given is 100 and Reverse of the given is 001, both are not equal, so its not a palindrome Number).
Level – Palindrome String. (Given and Reverse of the given is equal (Level and leveL)).
Link – Not a Palindrome String. (Given is Link and Reverse of the given is kniL, both are not equal, so its not a palindrome string).
Program to check Palindrome Number:
package com.ngdeveloper; public class NumberPalindrome { public static void main(String[] args) { int input = 100; checkPalindrome(input); } private static void checkPalindrome(int Number) { int i, j = 0; int input = Number; int check = input; do { i = input % 10; // 1 input = input / 10; // 1 j = j * 10 + i; // 10+1 } while (input > 0); if (check == j) { System.out.println("Palindrome Number"); } else { System.out.println("Not A Palindrome Number"); } } }
Output:
Input Given: 100
Not A Palindrome Number
Input Given: 101
Palindrome Number
Program to check a Palindrome String:
package com.ngdeveloper; public class StringPalindrome { public static void main(String[] args) { String input = "Level"; checkPalindrome(input); } private static void checkPalindrome(String input) { StringBuffer strBuf = new StringBuffer(input); StringBuffer reverse = (StringBuffer) strBuf.reverse(); if (input.toString().equalsIgnoreCase(reverse.toString())) { System.out.println("Palindrome String"); } else { System.out.println("Not A Palindrome String"); } } }
Output:
Given Input: Level
Palindrome String
Given Input: Link
Not A Palindrome String