《华为机试》刷题之HJ42 学英语

一、题目

在这里插入图片描述

二、示例

在这里插入图片描述

三、代码

list1 = ['zero','one','two','three','four','five','six','seven','eight',
         'nine','ten','eleven','twelve','thirteen','fourteen','fifteen',
         'sixteen','seventeen','eighteen','nineteen']
list2 = [0,0,'twenty','thirty','forty','fifty','sixty',
         'seventy','eighty','ninety']
def transfer(n):
    if n >= 100:
        result.append(list1[n // 100])
        result.append('hundred')
        if n % 100 != 0:
            result.append('and')
    n = n % 100
    if n > 0:
        if n < 20:
            result.append(list1[n])
        else:
            result.append(list2[n // 10])
            if n % 10 != 0:
                result.append(list1[n % 10])
while True:
    try:
        num = int(input())
        result = []
        l = num % 1000
        thous = (num // 1000) % 1000
        mill = (num // 1000000) % 1000
        bill = num // 1000000000
        if bill > 0:
            transfer(bill)
            result.append('billion')
        if mill > 0:
            transfer(mill)
            result.append('million')
        if thous > 0:
            transfer(thous)
            result.append('thousand')
        if l > 0:
            transfer(l)
        print(' '.join(result))
    except:
        break

四、算法说明

建立转换函数transfer,将每一个逗号分割的三位数字转换为英文表述;

  • 如果超过100,说明有千位,结果添加hundred字符;
  • 如果不是整百数,后面还有个位和十位,结果添加and字符;
  • 十位如果不超过20,直接在列表中读取,其他情况在列表中读取十位和个位。

主函数将数字按照billionmillionthousand,划分为三段,分别添加对应的字符。

打印输出。

胡萝卜

2022年2月15日13:25:06

我不知道将去向何方,但我已在路上!
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 !
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

O_胡萝卜_O

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值