Project Euler #17: 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.

Here is my solution in C++; an answer is surmised in .018 seconds

#include <iostream>
int main(void)
{
	unsigned long long letterCount = 11; // one thousand
	unsigned long long hundreds, tens, buff;
	std::string specialTens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
	std::string hundredsStrings[] = {"onehundred", "twohundred", "threehundred", "fourhundred", "fivehundred", "sixhundred", "sevenhundred", "eighthundred", "ninehundred"};
	std::string tensStrings[] = {"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"};
	std::string onesStrings[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
	for(unsigned long long i = 1; i <= 999; i++)
	{
                if(buff > 99)
		{
			hundreds = (buff / 100);
			buff %= 100;
			letterCount += hundredsStrings[hundreds-1].length();
			if(buff != 0)
			{
				letterCount += 3;
			}
		}
		if(buff >= 10)
		{
			if(buff < 20) 
                        { 
                               buff -= 10; letterCount += specialTens[buff].length(); buff = 0; 
                        } 
                        else 
                        { 
                               tens = (buff / 10); 
                               letterCount += tensStrings[tens-2].length(); buff %= 10; 
                        } 
                } 
                if(buff > 0)
		{
			letterCount += onesStrings[buff-1].length();
		}
	}

	std::cout << "Total letter count: " << letterCount << "\n";
	return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *