欧拉习题17

题目如下:

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.

依然还是动态规划的思路

代码如下:

clear;clc;close all
c = [3 3 5 4 4 3 5 5 4 3 6 6 8 8 7 7 9 8 8 6];
c(30:10:90) = [6 5 5 5 7 6 6];
c([100,1000]) = [10,11];
for i = 21 : 1000
    if c(i) > 0
        continue
    end
    if i < 100
        i1 = mod(i,10);
        i2 = i - i1;
        c(i) = c(i1) + c(i2);
    else 
        i1 = mod(i,100);
        i2 = floor(i/100);
        if i1 == 0
            c(i) = c(i2) + 7;
        else
            c(i) = c(i1) + c(i2) + 10;
        end
    end
end

PS: 程序可以优化的更加通用,由于时间关系,有兴趣读者可以继续优化代码,达到通用效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值