-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPE4.java
More file actions
68 lines (50 loc) · 1.17 KB
/
Copy pathPE4.java
File metadata and controls
68 lines (50 loc) · 1.17 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// https://projecteuler.net/problem=4
import java.util.ArrayList;
public class PE4
{
public static void main(String[] args)
{
System.out.println(new PE4().solution());
}
public int solution()
{
return maxPalindrome(3);
}
// Finds the maximum palindrome which is the product
// of two integers, each with d digits.
public int maxPalindrome(int d)
{
int maxPalindrome = 0;
int min = (int)Math.pow(10, d - 1);
int max = (int)Math.pow(10, d);
for (int i = min; i < max; i++)
for (int j = min; j < max; j++)
{
int n = i * j;
if (isPalindrome(n) && n > maxPalindrome)
maxPalindrome = n;
}
return maxPalindrome;
}
public boolean isPalindrome(int n)
{
ArrayList<Integer> digits = getDigits(n);
int d = digits.size();
for (int i = 0; i < (int)(d / 2); i++)
{
if (digits.get(i) != digits.get(d - i - 1))
return false;
}
return true;
}
public ArrayList<Integer> getDigits(int n)
{
ArrayList<Integer> digits = new ArrayList<Integer>();
while (n >= 1)
{
digits.add(n % 10);
n = (int)(n / 10);
}
return digits;
}
}