|
| 1 | +class Solution { |
| 2 | + public int largestPalindrome(int n) { |
| 3 | + // https://leetcode.com/problems/largest-palindrome-product/discuss/96297/Java-Solution-using-assumed-max-palindrom |
| 4 | + // if input is 1 then max is 9 |
| 5 | + if(n == 1){ |
| 6 | + return 9; |
| 7 | + } |
| 8 | + |
| 9 | + // if n = 3 then upperBound = 999 and lowerBound = 99 |
| 10 | + int upperBound = (int) Math.pow(10, n) - 1, lowerBound = upperBound / 10; |
| 11 | + long maxNumber = (long) upperBound * (long) upperBound; |
| 12 | + |
| 13 | + // represents the first half of the maximum assumed palindrom. |
| 14 | + // e.g. if n = 3 then maxNumber = 999 x 999 = 998001 so firstHalf = 998 |
| 15 | + int firstHalf = (int)(maxNumber / (long) Math.pow(10, n)); |
| 16 | + |
| 17 | + boolean palindromFound = false; |
| 18 | + long palindrom = 0; |
| 19 | + |
| 20 | + while (!palindromFound) { |
| 21 | + // creates maximum assumed palindrom |
| 22 | + // e.g. if n = 3 first time the maximum assumed palindrom will be 998 899 |
| 23 | + palindrom = createPalindrom(firstHalf); |
| 24 | + |
| 25 | + // here i and palindrom/i forms the two factor of assumed palindrom |
| 26 | + for (long i = upperBound; upperBound > lowerBound; i--) { |
| 27 | + // if n= 3 none of the factor of palindrom can be more than 999 or less than square root of assumed palindrom |
| 28 | + if (palindrom / i > maxNumber || i * i < palindrom) { |
| 29 | + break; |
| 30 | + } |
| 31 | + |
| 32 | + // if two factors found, where both of them are n-digits, |
| 33 | + if (palindrom % i == 0) { |
| 34 | + palindromFound = true; |
| 35 | + break; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + firstHalf--; |
| 40 | + } |
| 41 | + |
| 42 | + return (int) (palindrom % 1337); |
| 43 | + } |
| 44 | + |
| 45 | + private long createPalindrom(long num) { |
| 46 | + String str = num + new StringBuilder().append(num).reverse().toString(); |
| 47 | + return Long.parseLong(str); |
| 48 | + } |
| 49 | +} |
0 commit comments