forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp017.java
More file actions
59 lines (45 loc) · 1.47 KB
/
p017.java
File metadata and controls
59 lines (45 loc) · 1.47 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
/*
* Solution to Project Euler problem 17
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p017 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p017().run());
}
public String run() {
int sum = 0;
for (int i = 1; i <= 1000; i++)
sum += toEnglish(i).length();
return Integer.toString(sum);
}
private static String[] ONES = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; // Requires 0 <= n <= 9
private static String[] TEENS = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
private static String[] TENS = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
// Requires 0 <= n <= 99999
private static String toEnglish(int n) {
if (n < 0 || n > 99999)
throw new IllegalArgumentException();
if (n < 100)
return tens(n);
else {
String big = "";
if (n >= 1000)
big += tens(n / 1000) + "thousand";
if (n / 100 % 10 != 0)
big += ONES[n / 100 % 10] + "hundred";
return big + (n % 100 != 0 ? "and" + tens(n % 100) : "");
}
}
// Requires 0 <= n <= 99
private static String tens(int n) {
if (n < 10)
return ONES[n];
else if (n < 20) // Teens
return TEENS[n - 10];
else
return TENS[n / 10 - 2] + (n % 10 != 0 ? ONES[n % 10] : "");
}
}