[Project Euler] 来做欧拉项目练习题吧: 题目017
[Project Euler] 来做欧拉项目练习题吧: 题目017
周银辉
题目描述:
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.
问题分析:
这个题目比较简单哈,用铅笔和纸也比如容易算出啦。比如计算单个数字的出现次数,"hundred"单词出现的次数等等。
而用程序计算嘛,关键在于创建一个数字和对应单词长度的映射,也就是上面numbers那个数组。
#include <stdio.h>
int numbers[91];
void ini_numbers()
{
//为了节省空间,用hash_map也可以
numbers[0] = 0;//no pronunciation for zero
numbers[1] = 3;//"one"
numbers[2] = 3;//"two"
numbers[3] = 5;//"three"
numbers[4] = 4;//"four"
numbers[5] = 4;//"five"
numbers[6] = 3;//"six"
numbers[7] = 5;//"seven"
numbers[8] = 5;//"eight"
numbers[9] = 4;//"nine"
numbers[10] = 3;//"ten"
numbers[11] = 6;//"eleven"
numbers[12] = 6;//"twelve"
numbers[13] = 8;//"thirteen"
numbers[14] = 8;//"fourteen"
numbers[15] = 7;//"fifteen"
numbers[16] = 7;//"sixteen"
numbers[17] = 9;//"seventeen"
numbers[18] = 8;//"eighteen"
numbers[19] = 8;//"nineteen"
numbers[20] = 6;//"twenty"
numbers[30] = 6;//"thirty"
numbers[40] = 5;//"forty"
numbers[50] = 5;//"fifty"
numbers[60] = 5;//"sixty"
numbers[70] = 7;//"seventy"
numbers[80] = 6;//"eighty"
numbers[90] = 6;//"ninety"
}
int get_length(int n)
{
int a=0; //hundreds'digit
int b=0; //ten's digit
int c=0; //units' digit
int length = 0;
a = n/100;
n = n%100;
b = n/10;
c = n%10;
if(a!=0)
{
length += numbers[a] + 7; // 7 for "hundred"
if(b!=0 || c!=0)
{
length += 3; //3 for "and"
}
}
if(b!=0)
{
if(b==1)
{
length += numbers[b*10+c];
return length;
}
else
{
length += numbers[b*10];
}
}
if(c!=0)
{
length += numbers[c];
}
return length;
}
int main()
{
int i, length=0;
ini_numbers();
for(i=1; i<=999; i++)
{
length += get_length(i);
}
length += 11; //11 for "one thousand"
printf("total length: %d\n", length);
return 0;
}
分类:
Algorithm
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?