题解 | 人民币转换
用循环和栈来解决包括亿亿级以上的数字,不需要一直手动添加分类情况
一直除以一亿,直到商为0,把期间的模运算结果全部存到一个栈里,然后从栈顶开始处理每个模运算结果
#50156000002000123400120000.00
#st = [120000, 20001234, 15600000, 50]
import sys s = input() num,numdot = s.split('.') num = int(num) result = ['人民币'] dic = {'1':'壹','2':'贰','3':'叁','4':'肆','5':'伍','6':'陆','7':'柒','8':'捌', '9':'玖','0':'零'} def adjust(sub): res = [] if sub >= 1000: res.append(dic[str(sub)[0]]) res.append('仟') sub = sub % 1000 if 0 < sub < 100: res.append('零') if sub >= 100: res.append(dic[str(sub)[0]]) res.append('佰') sub = sub % 100 if 0 < sub < 10: res.append('零') if sub >= 10: if str(sub)[0] == '1': res.append('拾') else: res.append(dic[str(sub)[0]]) res.append('拾') sub = sub % 10 if sub > 0: res.append(dic[str(sub)[0]]) return ''.join(res) flag = True n1 = num st = [] while flag: n1,n2 = divmod(n1,100000000) st.append(n2) if not n1: flag = False #50156000002000123400120000.00 #st = [120000, 20001234, 15600000, 50] while st: n1 = st.pop() if n1 >= 10000: #万~千万 n2,n1 = divmod(n1,10000) #n2是千、百、十万、万,n1是千、百、十、个 tmp = adjust(n2) result.append(tmp) result.append('万') if n1 != 0: tmp = adjust(n1) result.append(tmp) if st: #st还有数,说明不是亿以内 result.append('亿') if num != 0: result.append('元') if numdot == '00': result.append('整') else: if numdot[0] != '0': result.append(dic[numdot[0]]) result.append('角') if numdot[1] != '0': result.append(dic[numdot[1]]) result.append('分') print(''.join(result))