欧拉计划 第十七题

本文介绍了一个通过C语言程序解决的问题:计算从1到1000的所有数字用英文表示时所需的字母总数。该程序利用数组存储了20以内及整十数的英文表示长度,并通过递归调用的方式实现了对任意三位数内数字的英文表示计算。

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到5用英字写出:一(one),二(two),三(three),四(four),五(five),则总共使用3 + 3 + 5 + 4 + 4 = 19个字母。

如果所有1到1000(一千)的数字都用文字写出来,会用多少个字母?

注意:不要计算空格或连字符。例如,342(三百四十二)包含23个字母,115(一百一十五)包含20个字母。在写出数字时使用“和”符合英国的用法。

思路

1.找规律:

(1)用两个数组分别把20以内所对应的英文,以及整十的数字记录下来;

(2)设定字符长度函数;

(3)在主函数中调用求和。

#include <stdio.h>

int num1[20] = {0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,8,8};
int num2[10] = {0,0,6,6,5,5,5,7,6,6};

int len(int num){
	if(num < 20){
		return num1[num];
	}else if(num < 100){
		return num1[num % 10] + num2[num /10];
	}else if(num < 1000){
		if(num % 100 == 0){
			return num1[num / 100] + 7;
		}else{
			return num1[num / 100] + len(num % 100) + 10;
		}
	}else{
		return 11;
	}
}

int main(){
	int sum = 0;
	for(int i = 1; i <= 1000; ++i){
		sum += len(i);
	}
	printf("%d\n", sum);
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值