Largest palindrome which is product of two N | Java implementation of the above approach ; Function to check if a number is a Palindrome or not ; Taking the string value of the number ; Loop to check if every i - th character from beginning is equal to every ( N - i ) th char ; Function to find the largest palindrome which is a product of two N digited numbers ; Find lowerBound , upperBound for a given nDigits . for n = 2 ; [ 10 , 99 ] ; Result variables ; Keep p decrementing by 11 ; Find the nearest number divisible by 11 ; Keep decrementing q by 1 ; Update the result if t > r and is a palindrome ; Printing the final result ; Driver code
public class GFG { static boolean isPalindrome ( long x ) { String num = String . valueOf ( x ) ; boolean result = true ; int i = 0 ; int j = num . length ( ) - 1 ; while ( i < j && result ) { result = num . charAt ( i ++ ) == num . charAt ( j -- ) ; } return result ; } public static void find ( final int nDigits ) { final long lowerBound = ( long ) Math . pow ( 10 , nDigits - 1 ) ; final long upperBound = ( lowerBound * 10 ) - 1 ; long resultP = 0 , resultQ = 0 , resultR = 0 ; for ( long p = upperBound ; p > lowerBound ; p -= 11 ) { while ( p % 11 != 0 ) { p -- ; } for ( long q = upperBound ; q > lowerBound ; q -- ) { long t = p * q ; if ( t > resultR && isPalindrome ( t ) ) { resultP = p ; resultQ = q ; resultR = t ; break ; } } } System . out . println ( resultR ) ; } public static void main ( String [ ] args ) { int N = 2 ; find ( N ) ; } }