Project Euler17.数字1,2,3使用英文的表示为one,two,three,使用的英文的字母数的总和为3+3+5=11,现有1到1000,使用的英文字母数总和为多少?(空格和连接符不计)

该博客探讨了Project Euler第17题的解决方案,即计算从1到1000所有数字用英文表示时的字母总数。博主通过观察数字与英文表示的规律,创建了特定的字符串数组,并设计了一个算法来处理个位、十位和百位的特殊情况,最后计算出总字母数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先我们观察到1-1000这些数字英文表示存在规律,例如121为 one hundred and twenty-one可分为one hundred and+ twenty+one,因此我们在记录数字英文表示的时候,只需要知道个位,十位和百位的数字就行。接下来需要特殊处理的数字有1-19,20,30直到90。数字处理如下:

定义一个数组

string m[20]={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}

string n[10]={"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};

算法:

  1. 初始处理:(其中1<= i < 1000)

    a=i%10;//个位数字

    b=(i%100)/10;//十位

    c=i/100;//百位

  2. 循环开始1<= i < 1000
    • 如果i%100==0,three=m[c]+7,否则,three=m[c].Length()+7+3;
    • 如果b==1,sencond=m[b],first=0,否则,second=n[b].Length(),first=m[a].Length();
    • sum=first+second+three;
    • 循环结束

程序代码:

#include <IOSTREAM>
#include <CSTRING>
using namespace std;
const string m[20]={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
const string n[10]={"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
int main()
{

	int first,second,three,sum=0;
	for (int i=1;i<1000;++i)
	{
		int a=i%10;//个位数字		
		int b=(i%100)/10;//十位
		int c=i/100;//百位

		if(c >= 1)
		{
			three = m[c].length() + 7;
			if(i % 100 != 0)
				three += 3;
		}
		else
			three = 0;
		
		if(b >= 2)
		{
			second = n[b].length();
			first = m[a].length();
		}
		else
		{
			second = 0;
			first = m[i % 100].length();
		}
		sum = sum + first + second + three;
	}
	sum+=11;
	cout<<sum<<endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值