Thursday, April 24, 2008

Project Euler Problem 17

Definition:
---------------------------------------------
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.

---------------------------------------------

C# code solution:



static long LettersOfNumber(long num, long[,]bases)
{
long count = 0;
long tempnum;
if (num > 1000 num < 1)
count = -1;
else if (num == 1000)
count = 11;
else
{
tempnum = num % 100;
if (tempnum < 20)
count += bases[tempnum, 0];
else
count += bases[num % 10, 0] + bases[(num / 10) % 10, 1];
if (num > 99)
count += bases[(num / 100), 0] + 7 + ((tempnum == 0) ? 0 : 3);
}
return count;
}
static long LettersUntilNumber(int num)
{
long letcount = 0;
long[,] bas = new long[20, 2] { {0, 0}, {3, 0}, {3, 6}, {5, 6}, {4, 5}, {4, 5}, {3, 5}, {5, 7},
{5, 6}, {4, 6}, {3, 0}, {6, 0}, {6, 0}, {8, 0}, {8, 0}, {7, 0},
{7, 0}, {9, 0}, {8, 0}, {8, 0} };
for (int i = 1; i <= num; i++)
letcount += LettersOfNumber(i, bas);
return letcount;
}
static void Main(string[]args)
{
Console.WriteLine(LettersUntilNumber(1000));
Console.ReadLine();
}


No comments:

Post a Comment

Comment will be posted after comment moderation.
Thank you for your appreciation.