13 July, 2019

Find all possible palindromes in an array

In this article, we will see how to find all palindrome from an array. This is a very basic questions in interview, the interviewer will ask the same questions in different way. So, its good to know all possible questions from palindrome. Also there is a question to find all palindrome number from a list.  Find few more collection interview question.  Today we will see how to check a number is palindrome or not. 


FindAllPalindrome.java

package com.javadevelopersguide.lab.basic;
/**
 * This program illustrates find all palindrome from array.
 *
 * @author manoj.bardhan
 *
 */
public class FindAllPalindrome {
public static void main(String[] args) {
int numberArray[] = { 120, 990, 121, 777, 808, 1280 };
for (int i = 0; i < numberArray.length; i++) {
printOnlyPalindrom(numberArray[i]);
}
}
private static void printOnlyPalindrom(int number) {
int finalNumber = 0;
int oldNumber = number;
// Repeat the loop until the number became zero.
while (number != 0) {
// Get the First Digit (i.e. 1)
int firstDigit = number % 10;
// Get the Result number.
finalNumber = (finalNumber * 10) + firstDigit;
// Now get the remaining digits , after finding the first digit
number = number / 10;
}
// Now compare the finalNumber and oldNumber both are same or not.
if (finalNumber == oldNumber)
System.out.println(finalNumber + " is a Palindrome.");
}
}

Output -

121 is a Palindrome.
777 is a Palindrome.
808 is a Palindrome.


2 comments: