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


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

主要是考虑几种特殊的数字比如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;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值