码迷,mamicode.com
首页 > 其他好文 > 详细

Project Euler: Problem 17 Number letter counts

时间:2015-05-31 12:33:14      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:project euler   c++   

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.


首先要知道数字对应的英文是什么

主要是考虑几种特殊的数字比如1-20 以及能被10整除的数,因为可以用一个单词表示出来。对于其它100以内的数可以可以用两个单词表示出来。

对于三位数,整百的可以用2个单词表示,其它的 X hundred and X (X) 这种结构。

四位数只有一个1000 :one thousand



#include <iostream>
#include <string>
#include <map>
using namespace std;

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

	int len[1001];
	map<int, string>::iterator iter;
	for (iter = mp.begin(); iter != mp.end(); iter++)
	{
		len[iter->first] = iter->second.length();
	}

	for (int i = 21; i <= 99; i++)  // 35 thirteen five
	{
		if (i % 10 != 0)
		{
			int low = i % 10;
			int high = i - low;
			len[i] = len[low] + len[high];
		}
	}

	for (int i = 100; i <= 999; i++)
	{
		if (i % 100 == 0)   //700 seven hundred 
		{
			int high = i / 100;
			len[i] = len[high] + 7;
		}
		else               //342 three hundred and fourty two
		{
			int high = i / 100;
			int low = i % 100;
			len[i] = len[high] + 7 + 3 + len[low];
		}
	}

	len[1000] = 11;

	int res = 0;
	for (int i = 1; i <= 1000; i++)
		res += len[i];
	cout << res << endl;
	system("pause");
	return 0;
}




Project Euler: Problem 17 Number letter counts

标签:project euler   c++   

原文地址:http://blog.csdn.net/youb11/article/details/46285323

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!