Skip to content

Instantly share code, notes, and snippets.

@deniskyashif
Created October 23, 2015 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deniskyashif/f5753a0bb6a822774e67 to your computer and use it in GitHub Desktop.
Save deniskyashif/f5753a0bb6a822774e67 to your computer and use it in GitHub Desktop.
/*
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.
*/
using System;
class Program
{
static string GetNumberName(int input)
{
var output = new System.Text.StringBuilder();
string[] fromOneToNineteen = {"", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" };
string[] decimalsNames = {"", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};
string[] hundredsNames = {"", "onehundred", "twohundred", "threehundred", "fourhundred",
"fivehundred", "sixhundred", "sevenhundred", "eighthundred", "ninehundred"};
int hundreds = input / 100;
int decimals = (input / 10) - hundreds * 10;
int units = input % 10;
if (input >= 100 && input <= 999)
{
if (decimals < 2)
{
if (units == 0 && decimals == 0)
{
output.Append(hundredsNames[hundreds]);
}
else
{
output.AppendFormat("{0}and{1}", hundredsNames[hundreds], fromOneToNineteen[input % 100]);
}
}
else
{
output.AppendFormat("{0}and{1}{2}", hundredsNames[hundreds],
decimalsNames[decimals], fromOneToNineteen[units]);
}
}
else if (input >= 20 && input <= 99)
{
output.AppendFormat("{0}{1}", decimalsNames[decimals], fromOneToNineteen[units]);
}
else if (input >= 0 && input < 20)
{
if (input == 0)
{
output.AppendFormat("zero");
}
output.AppendFormat("{0}", fromOneToNineteen[input]);
}
else if (input == 1000)
{
return "onethousand";
}
return output.ToString();
}
static void Main()
{
int lettersCount = 0;
for (int i = 1; i <= 1000; i++)
{
lettersCount += GetNumberName(i).Length;
}
Console.WriteLine(lettersCount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment