Solution for the Project Euler Problem 17:
"
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."
<?php
class GetNumber
{
public $word;
public $number;
public $words = array(
0 => '',
1 => 'One',
2 => 'Two',
3 => 'Three',
4 => 'Four',
5 => 'Five',
6 => 'Six',
7 => 'Seven',
8 => 'Eight',
9 => 'Nine',
10 => 'Ten',
11 => 'Eleven',
12 => 'Twelve',
13 => 'Thirteen',
14 => 'Fourteen',
15 => 'Fifteen',
16 => 'Sixteen',
17 => 'Seventeen',
18 => 'Eighteen',
19 => 'Nineteen',
20 => 'Twenty',
30 => 'Thirty',
40 => 'Forty',
50 => 'Fifty',
60 => 'Sixty',
70 => 'Seventy',
80 => 'Eighty',
90 => 'Ninety',
100 => 'Hundred',
1000 => 'Thousand'
);
function roll($num)
{
$this->word = '';
$this->number = (int)$num;
$length = strlen($this->number);
if ($length >= 4) {
$this->thousands();
}
else if ($length > 1) {
if ($length >= 3) {
$this->hundreds();
}
if ($length >= 2) {
$this->tens();
}
} else {
$this->singles();
}
echo $this->word . '<br />';
return $this->display();
}
function singles()
{
$this->word .= $this->words[$this->number];
}
function tens()
{
$tens = substr($this->number, -2);
if (abs($tens) > 0) {
if (($tens % 10) == 0) {
$this->word .= $this->words[$tens[0]*10];
} else if ($tens <= 20) {
$this->word .= $this->words[abs($tens)];
} else {
$this->word .= $this->words[$tens[0]*10] . $this->words[$tens[1]];
}
}
}
function hundreds()
{
$hunds = substr($this->number, -3);
if ($hunds[0] > 0) {
$this->word .= $this->words[$hunds[0]] . $this->words[100];
if ($hunds[1] != 0 || $hunds[2] != 0) {
$this->word .= 'And';
}
}
}
function thousands()
{
$hunds = substr($this->number, -4);
$this->word .= $this->words[$hunds[0]] . $this->words[1000];
}
function display()
{
return strlen($this->word);
}
}
$a = new GetNumber();
$count = 0;
for($i = 1; $i <= 1000; $i++) {
$count += $a->roll($i);
}
echo $count;
?>
Copy to Clipboard