Description
Get an array as the input from the user and find the longest palindrome in that array.
Input
Enter the size of array
3
Enter the elements of array
121 10456 1000001
Output
1000001
C Program
#include<stdio.h>
#include<limits.h>
int check(int n){
int rev=0, temp = n;
while(temp>0)
{
int rem = temp%10;
rev = rev*10 + rem;
temp /= 10;
}
if(n==rev)
return 1;
return 0;
}
int main(){
int n;
printf("Enter the size of array: ");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of array: ");
for(int i=0;i<n;i++)
scanf("%d",&arr[i]);
int res = INT_MIN;
for(int i=0; i<n; i++)
{
if(check(arr[i]) && res<arr[i])
res = arr[i];
}
if(res==INT_MIN)
res = -1;
printf("Longest palindrome: %d ",res);
}
C++ Program
#include<iostream>
#include<limits.h>
using namespace std;
int check(int n){
int rev=0, temp = n;
while(temp>0)
{
int rem = temp%10;
rev = rev*10 + rem;
temp /= 10;
}
if(n==rev)
return 1;
return 0;
}
int main(){
int n;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n];
cout<<"Enter the elements of array: ";
for(int i=0;i<n;i++)
cin>>arr[i];
int res = INT_MIN;
for(int i=0; i<n; i++)
{
if(check(arr[i]) && res<arr[i])
res = arr[i];
}
if(res==INT_MIN)
res = -1;
cout<<"Longest palindrome: "<<res;
}
Java Program
import java.util.*;
class Main
{
static boolean check(int n)
{
int div = 1;
while (n / div >= 10)
div *= 10;
while (n != 0) {
int x = n / div;
int y = n % 10;
if (x != y)
return false;
n = (n % div) / 10;
div = div / 100;
}
return true;
}
static int largestPal(int []arr, int n)
{
int res = -1;
for (int i = 0; i < n; i++)
{
if (arr[i] > res && check(arr[i]))
res = arr[i];
}
return res;
}
public static void main(String []args)
{
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
n = sc.nextInt();
int[]arr = new int[n];
System.out.println("Enter the array elements: ");
for(int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Longest Palindrome: "+largestPal(arr, n));
}
}
Python Program
def check(n):
div = 1
while (int(n / div) >= 10):
div *= 10
while (n != 0):
front = int(n / div)
rear = n % 10
if (front != rear):
return False
n = int((n % div) / 10)
div = int(div / 100)
return True
def largestPal(arr, n):
result = -1
for i in range(0, n, 1):
if (arr[i] > result and check(arr[i])):
result = arr[i]
return result
n = int(input("Enter size of array: "))
arr = []
print("Enter array elements: ")
for i in range(0,n):
temp = int(input())
arr.append(temp)
print("Longest Palindrome: ",largestPal(arr, n))