一、题目
二、示例
三、代码
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,直接在列表中读取,其他情况在列表中读取十位和个位。
主函数将数字按照billion
,million
,thousand
,划分为三段,分别添加对应的字符。
打印输出。
胡萝卜
2022年2月15日13:25:06
我不知道将去向何方,但我已在路上! |
---|
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 ! |