题目

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.

解答

首先是把数字对应的单词的长度记录一下,也就是下面代码里的n1n10n11n这几个tupple。因为整个程序是只能算1000以内,所以加了句如果超出就报错的语句。然后我们就可以对数字进行拆解,再从这几个tupple里对应一个长度,加和一下,就可以把输入的数字转换成英文的字符串长度。

import sys  
  
def nchar(x):  
    if (x > 1000):  
        print("x should be less than 1000...")  
        sys.exit(0)  
    n1=(0,3,3,5,4,4,3,5,5,4)    # 1 to 9  
    n10=(0,3,6,6,5,5,5,7,6,6)   # 10 to 90  
    n11=(0,6,6,8,8,7,7,9,8,8)   # 11 to 19  
    n=(7,10,11) # hundred, hundred and, one thousand  
    if (x == 1000):  
        return n[2]  
    elif (x % 100 == 0):  
        return n1[x // 100] + n[0]  
    elif (x > 100):  
        y = x % 100  
        return n1[x // 100] + n[1] + nchar(x % 100)  
    elif (x < 10):  
        return n1[x]  
    elif (x == 10):  
        return n10[1]  
    elif (x >= 11and x <= 19):  
        return n11[x-10]  
    elif (x >= 20and x < 100):  
        return n10[x // 10] + n1[x % 10]  
    else:  
        return0

有了这个函数,那么就可以遍历需要计算的所有数,也是一个加和,就统计完成了。

def solution17(N):  
    res = 0  
    for i in range(1, N+1):  
        res += nchar(i)  
  
    return(res)