《华为机试》刷题之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 tempdef 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 tempdef 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 tempdef 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 tempwhile True:try:yuan, jiaofen = input().split('.')yuan = int(yuan)result = []a = yuan // 100000000b = (yuan // 10000) % 10000c = yuan % 10000if 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

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


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部