Problem Description
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
Analysis
Converted the integers from 1 to 999 to the written equivalent, removed spaces and hyphens, added the character count for each one, including “onethousand”.
Solution
Runs < 1 second in Perl.
@D{0 .. 20, 30,40,50,60,70,80,90} = qw| zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety|; for $i (1..999) { $x= num2en($i); $x=~s/[s-]//g; $l+= length($x); } print "Answer to PE17 = ",$l+length('onethousand'); sub num2en { my($x) = $_[0]; return $D{$x} if defined $D{$x}; return $D{$1 . '0'} . '-' . $D{$2} if( $x =~ m/^(.)(.)$/ ); if ( $x =~ m/^(.)(..)$/ ) { my($h, $rest) = ("$D{$1} hundred", $2); return $h if $rest eq '00'; return "$h and " . num2en($rest); } }





Discussion
No comments for “Project Euler Problem 17 Solution”