GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/java/479_Largest_Palindrome_Product.java at master · ffortunado/leetcode

Expand file tree

/

479_Largest_Palindrome_Product.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
49 lines (40 loc) · 1.88 KB
/

479_Largest_Palindrome_Product.java

Copy path

File metadata and controls

49 lines (40 loc) · 1.88 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public int largestPalindrome(int n) {
// https://leetcode.com/problems/largest-palindrome-product/discuss/96297/Java-Solution-using-assumed-max-palindrom
// if input is 1 then max is 9
if(n == 1){
return 9;
}
// if n = 3 then upperBound = 999 and lowerBound = 99
int upperBound = (int) Math.pow(10, n) - 1, lowerBound = upperBound / 10;
long maxNumber = (long) upperBound * (long) upperBound;
// represents the first half of the maximum assumed palindrom.
// e.g. if n = 3 then maxNumber = 999 x 999 = 998001 so firstHalf = 998
int firstHalf = (int)(maxNumber / (long) Math.pow(10, n));
boolean palindromFound = false;
long palindrom = 0;
while (!palindromFound) {
// creates maximum assumed palindrom
// e.g. if n = 3 first time the maximum assumed palindrom will be 998 899
palindrom = createPalindrom(firstHalf);
// here i and palindrom/i forms the two factor of assumed palindrom
for (long i = upperBound; upperBound > lowerBound; i--) {
// if n= 3 none of the factor of palindrom can be more than 999 or less than square root of assumed palindrom
if (palindrom / i > maxNumber || i * i < palindrom) {
break;
}
// if two factors found, where both of them are n-digits,
if (palindrom % i == 0) {
palindromFound = true;
break;
}
}
firstHalf--;
}
return (int) (palindrom % 1337);
}
private long createPalindrom(long num) {
String str = num + new StringBuilder().append(num).reverse().toString();
return Long.parseLong(str);
}
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.