Number letter counts

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.

Solution:


void Solution()
{
 Dictionary<int, string> numbers = new Dictionary<int, string>();
 numbers.Add(1, "one");
 numbers.Add(2, "two");
 numbers.Add(3, "three");
 numbers.Add(4, "four");
 numbers.Add(5, "five");
 numbers.Add(6, "six");
 numbers.Add(7, "seven");
 numbers.Add(8, "eight");
 numbers.Add(9, "nine");
 numbers.Add(10, "ten");
 numbers.Add(11, "eleven");
 numbers.Add(12, "twelve");
 numbers.Add(13, "thirteen");
 numbers.Add(14, "fourteen");
 numbers.Add(15, "fifteen");
 numbers.Add(16, "sixteen");
 numbers.Add(17, "seventeen");
 numbers.Add(18, "eighteen");
 numbers.Add(19, "nineteen");
 numbers.Add(20, "twenty");
 numbers.Add(30, "thirty");
 numbers.Add(40, "forty");
 numbers.Add(50, "fifty");
 numbers.Add(60, "sixty");
 numbers.Add(70, "seventy");
 numbers.Add(80, "eighty");
 numbers.Add(90, "ninety");
 numbers.Add(100, "hundred");
 numbers.Add(1000, "thousand");

 int sum = 0;
 for (int i = 1; i <= 20; i++)
 {
  sum += numbers[i].Length;
  Console.WriteLine(numbers[i] + " " + numbers[i].Length);
 }

 for (int i = 21; i < 100; i++)
 {
  int key = i / 10;
  if (i % 10 != 0)
   sum += numbers[key * 10].Length + numbers[i % 10].Length;
  else
   sum += numbers[key * 10].Length;
 }

 int sumTill1To99 = sum;

 for (int i = 101; i < 999; i = i + 100)
 {
  int key = i / 100;
  sum += numbers[key].Length + numbers[100].Length;
  sum += (numbers[key].Length + numbers[100].Length + "and".Length) * 99;
  sum = sum + sumTill1To99;

 }

 sum = sum + numbers[1].Length + numbers[1000].Length;
}

No comments :

Post a Comment

Comment Here