《华为机试》刷题之HJ95 人民币转换

一、题目

在这里插入图片描述

二、示例

在这里插入图片描述

三、代码

list1 = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖','拾',
        '拾壹','拾贰','拾叁','拾肆','拾伍','拾陆','拾柒','拾捌','拾玖']
def fun100(num):  # 100以内的数字转换
    temp = []
    if num < 20:
        if num < 10:
            temp.append('零')
        temp.append(list1[num])
    else:
        temp.append(list1[num // 10])
        temp.append('拾')
        if num % 10 != 0:
            temp.append(list1[num % 10])
    return temp

def fun1000(num):  # 1000以内的数字转换
    temp = []
    if num < 100:
        temp.append('零')
        temp += fun100(num)
    else:
        temp.append(list1[num // 100])
        temp.append('佰')
        if num % 100 != 0:
            if num % 100 < 10:
                temp.append('零')
            temp += fun100(num % 100)
    return temp

def fun10000(num):  # 10000以内的数字转换
    temp = []
    if num < 1000:
        temp.append('零')
        temp += fun1000(num)
    else:
        temp.append(list1[num // 1000])
        temp.append('仟')
        if num % 1000 != 0:
            if num % 1000 < 100:
                temp.append('零')
            temp += fun1000(num % 1000)
    return temp

def decimals(num):  # 小数部分数字转换
    temp = []
    if num[0] != '0':
        temp.append(list1[int(num[0])])
        temp.append('角')
    if num[1] != '0':
        temp.append(list1[int(num[1])])
        temp.append('分')
    return temp

while True:
    try:
        yuan, jiaofen = input().split('.')
        yuan = int(yuan)
        result = []
        a = yuan // 100000000
        b = (yuan // 10000) % 10000
        c = yuan % 10000
        if a > 0:
            result += fun10000(a)
            result.append('亿')
        if b > 0:
            result += fun10000(b)
            result.append('万')
        if c > 0:
            result += fun10000(c)
        if len(result) > 0:
            result.append('元')
        if int(jiaofen) == 0:
            result.append('整')
        else:
            result += decimals(jiaofen)
        res = ''.join(result)
        res = res.replace('零零','零')  # replace() 用另一个指定的短语替换一个指定的短语。
        res = res.strip('零')  # strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
        print('人民币' + res)
    except:
        break

四、算法说明

分别建立100,1000,10000以内的数字转换子函数;
然后将整数部分调用各个子函数,进行转化;
数字位数差两位就加‘零’,用‘零’替换‘零零’,再把头部的‘零’去掉。

注意:
replace() 方法用另一个指定的短语替换一个指定的短语;
strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

胡萝卜

2022年2月28日21:33:19

我不知道将去向何方,但我已在路上!
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 !
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

O_胡萝卜_O

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

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

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

打赏作者

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

抵扣说明:

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

余额充值