题目如下:
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: 程序可以优化的更加通用,由于时间关系,有兴趣读者可以继续优化代码,达到通用效果