Skip to content

Commit c315b3e

Browse files
committed
largest panlindrome product
1 parent 2128daa commit c315b3e

File tree

3 files changed

+84
-35
lines changed

3 files changed

+84
-35
lines changed

.idea/workspace.xml

Lines changed: 36 additions & 35 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@ codes may not be optimized
403403
1. [Path Sum III](https://leetcode.com/problems/path-sum-iii/description/)
404404
1. [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/)
405405
1. [Repeated Substring Patterns](https://leetcode.com/problems/repeated-substring-pattern/description/)
406+
1. [Largest Panlindrome Product](https://leetcode.com/problems/largest-palindrome-product/description/)
406407

407408
### Day 19 - Medium
408409

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.github.chen0040.leetcode.day19.easy;
2+
3+
4+
/**
5+
* Created by xschen on 14/8/2017.
6+
*
7+
* link: https://leetcode.com/problems/largest-palindrome-product/description/
8+
*/
9+
public class LargestPanlinedromeProduct {
10+
public class Solution {
11+
public int largestPalindrome(int n) {
12+
13+
if(n == 1) return 9;
14+
15+
int upperBound = (int)Math.pow(10, n) - 1;
16+
int lowerBound = (int)Math.pow(10, n-1);
17+
18+
long maxNumber = (long)upperBound * (long)upperBound;
19+
20+
int firstHalf = (int)(maxNumber / (long)Math.pow(10, n));
21+
while(true) {
22+
long candidate = createPanlindrome(firstHalf);
23+
for(long i = upperBound; i >= lowerBound; --i) {
24+
if (i * i < candidate) {
25+
break;
26+
}
27+
28+
if(candidate % i == 0) {
29+
return (int)(candidate % 1337);
30+
}
31+
}
32+
firstHalf--;
33+
if(firstHalf < 0) break;
34+
}
35+
return -1;
36+
}
37+
38+
long createPanlindrome(int firstHalf) {
39+
StringBuilder sb = new StringBuilder();
40+
sb.append(firstHalf);
41+
sb.reverse();
42+
String str = firstHalf + sb.toString();
43+
return Long.parseLong(str);
44+
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)