华为机试 HJ96 python

人民币转换

http://www.nowcoder.com/questionTerminal/00ffd656b9604d1998e966d555005a4b

对中间有多个0的处理方式,对末尾有0的处理方式的一些思考。
以上,供参考

def func(x)->str:
    res = []
    zero_pre = False # 确保在连续‘0’的情况下,只有一个'零'
    for i, xi in enumerate(x[::-1]): # 倒着转化
        if xi=='0':
            if not zero_pre:
                res.append(num[int(xi)])
                zero_pre = True
        else:
            zero_pre = False
            res.extend([pro[i], num[int(xi)]])
    res = res[::-1]
#     print(res)
    while res[-1]=='零':# 去掉后面所有的 ”零“
        res.pop()
    return ''.join(res).replace('壹拾', '拾')

num = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖']
pro = ['', '拾','佰','仟','万','亿','元','角','分','整']
while True:
    try:
        n, m = input().strip().split('.')

        res = ['人民币']
        if len(n)>8:
            res.append(func(n[:-8])+'亿')
        if len(n)>4:
            res.append(func(n[-8:-4])+'万')
        if n!='0':
            res.append(func(n[-4:])+'元')

        if m=='00':
            res.append('整')
        else:
            if m[0]>'0':
                res.append(num[int(m[0])]+'角')
            if m[1]>'0':
                res.append(num[int(m[1])]+'分')

        print(''.join(res))
    except:
        break

"""
0.85
0.25
人民币捌角伍分
人民币贰角伍分

1024.56
10012.02
100110.00
30105000.00

人民币壹仟零贰拾肆元伍角陆分
人民币壹万零拾贰元贰分
人民币拾万零壹佰拾元整
人民币叁仟零拾万伍仟元整
"""

全部评论
有问题,像10000.00,100000.00等都无法输出,还有位数超过12位就非法了
点赞 回复 分享
发布于 2021-08-27 16:53

相关推荐

未知的命运:大佬这都找不到我还找啥啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务