Skip to content

Commit 6c54e53

Browse files
authored
Merge pull request #15 from educationalgamer/main
Finding the Longest Palindrome in an Array
2 parents cd46714 + 34e41e6 commit 6c54e53

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import java.util.*;
2+
3+
class Main
4+
{
5+
// Function to check if n is palindrome
6+
static boolean isPalindrome(int n)
7+
{
8+
// Find the appropriate divisor
9+
// to extract the leading digit
10+
int divisor = 1;
11+
while (n / divisor >= 10)
12+
divisor *= 10;
13+
14+
while (n != 0) {
15+
int x = n / divisor;
16+
int y = n % 10;
17+
18+
// If first and last digits are
19+
// not same then return false
20+
if (x != y)
21+
return false;
22+
23+
// Removing the leading and trailing
24+
// digits from the number
25+
n = (n % divisor) / 10;
26+
27+
// Reducing divisor by a factor
28+
// of 2 as 2 digits are dropped
29+
divisor = divisor / 100;
30+
}
31+
return true;
32+
}
33+
34+
// Function to find the largest palindromic number
35+
static int largestPalindrome(int []A, int n)
36+
{
37+
int res = -1;
38+
39+
for (int i = 0; i < n; i++) { // If a palindrome larger than the currentMax is found
40+
if (A[i] > res && isPalindrome(A[i]))
41+
res = A[i];
42+
}
43+
44+
// Return the largest palindromic number from the array
45+
return res;
46+
}
47+
48+
// Driver program
49+
public static void main(String []args)
50+
{
51+
int []A = { 121, 2322, 54545, 999990 };
52+
int n = A.length;
53+
54+
// print required answer
55+
System.out.println(largestPalindrome(A, n));
56+
}
57+
58+
}

0 commit comments

Comments
 (0)