题解 | #学英语#

num1 = ['zero','one','two','three','four','five','six',
       'seven','eight','nine','ten','eleven','twelve',
       'thirteen','fourteen','fifteen','sixteen',
       'seventeen','eighteen','nineteen']
num2 = [0,0,'twenty','thirty','forty','fifty','sixty',
       'seventy','eighty','ninety']  # 前面两个0,是为了下标方便取数
gj = ['and', 'hundred', 'thousand', 'million', 'billion']

def ge(s): # 处理0~19
    return num1[int(s)]

def sw(s): # 处理20~99
    if 0 <= int(s) <= 19:
        return ge(s)
    elif s[-1] == '0':  # 处理整数
        return num2[int(s[0])]
    else:  # 处理非整数
        tens = num2[int(s[0])]  # 十位数
        ges = num1[int(s[1])]  # 个位数
        return tens + ' ' + ges

def hun(s):
    if 0 <= int(s) <= 19:
        return ge(s)
    elif 20 <=int(s) < 100:
        return sw(s)
    elif 100 <= int(s) < 1000:
        hu = ''
        sws = ''
        hu = num1[int(s[0])] + ' ' + gj[1]
        if s[1:] == '00': #处理整百
            return hu
        else:
            sws = sw(s[1:])
    return hu + ' ' + gj[0] + ' ' + sws


def thou(s):
    # 在这里调用hun即可,注意百位为0的判断
    s1 = s[1]
    s2 = s[0]
    th = '' # 存储千位
    hu = '' # 存储百位
    # 先处理thousand
    th = hun(s1) + ' ' + gj[2]
    # 再处理hundred
    if s2 == '000':
        hu = ''
    elif s2[:2] == '00': # 处理百位和十位都为0的情况
        hu = ' ' + hun(s2[-1])
    elif s2[0] == '0': # 处理百位为0的情况
        hu = ' ' + hun(s2[1:])
    else: # 正常处理
        hu = ' ' + hun(s2)
    return th + hu


# 1,652,510:  one million six hundred and fifty two thousand five hundred and ten
def mil(s):
    s1 = s[2]
    s2 = s[1]
    s3 = s[0]
    mil = ''
    th_hun = ''
    # 先处理million
    mil = hun(s1) + ' ' + gj[3]
    if s2 == '000' and  s3 == '000':
        th_hun = ''
    elif s2 == '000': # thousand 全部为0
        th_hun = ' ' + hun(s3)
    else:
        th_hun = thou(s[:-1])
        th_hun = ' ' + thou(s[:-1])
    return mil + th_hun


while True:
    try:
        s = input()
        res = []
        if len(s) > 3:
            for i in range(len(s) // 3):
                res.append(s[-3:])
                s = s[:-3]
            if len(s) > 0:
                res.append(s)
        else:
            res.append(s)
        # print(res)
        if len(res) == 1:
            # print(res[0])
            print(hun(res[0]))
        elif len(res) == 2:
            print(thou(res))
        else:
            print(mil(res))
    except:
        break
全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-24 20:55
阿里国际 Java工程师 2.7k*16.0
程序员猪皮:没有超过3k的,不太好选。春招再看看
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务