-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheuler-017
44 lines (38 loc) · 1.24 KB
/
euler-017
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
# Map numbers to their word representations
NUMBER_WORDS = {
90 => "ninety", 80 => "eighty", 70 => "seventy", 60 => "sixty",
50 => "fifty", 40 => "forty", 30 => "thirty", 20 => "twenty",
19 => "nineteen", 18 => "eighteen", 17 => "seventeen", 16 => "sixteen",
15 => "fifteen", 14 => "fourteen", 13 => "thirteen", 12 => "twelve",
11 => "eleven", 10 => "ten", 9 => "nine", 8 => "eight", 7 => "seven",
6 => "six", 5 => "five", 4 => "four", 3 => "three", 2 => "two", 1 => "one"
}.freeze
def humanize(number)
parts = []
# Handle thousands
if number >= 1000
parts << "#{NUMBER_WORDS[number / 1000]}thousand"
number %= 1000
end
# Handle hundreds
if number >= 100
parts << "#{NUMBER_WORDS[number / 100]}hundred"
number %= 100
parts << "and" if number > 0
end
# Handle tens and ones
if number > 0
if NUMBER_WORDS.key?(number)
parts << NUMBER_WORDS[number]
else
tens = (number / 10) * 10
ones = number % 10
parts << NUMBER_WORDS[tens]
parts << NUMBER_WORDS[ones] if ones > 0
end
end
parts.join('')
end
# Calculate total character count for numbers 1 to 1000
character_count = (1..1000).sum { |n| humanize(n).length }
puts "The character count is #{character_count}"