首页 > 试题广场 >

编程

[编程题]编程
  • 热度指数:102 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
实现函数,能对数字进行千分位格式化和大写金额转化

输入描述:
1400398


输出描述:
1,400,398 壹佰肆拾萬零叁佰玖拾捌
示例1

输入

1400398

输出

1,400,398 壹佰肆拾萬零叁佰玖拾捌

def wan(ip): #万以内大写转换 #ip为要转换的数字
    it=['拾','佰','仟']
    if set(ip)=={'零'}:
        return '#'
    elif ip[-1]=='零' and ip[-2]!='零':
        ip[-1]='拾'
    elif ip[-1]=='零' and ip[-2]=='零' and ip[-3]!='零':
        ip.pop(-1)
        ip[-1]='佰'
        if ip[0]=='零' and ip[1]=='零':
            ip.pop(0)
    elif ip[-1]=='零' and ip[-2]=='零' and ip[-3]=='零' and ip[-4]!='零':
        ip.pop(-1)
        ip.pop(-1)
        ip[-1]='仟'
    for j in range(1,len(ip)):
        ip.insert(-j*2+1, it[(j-1)%3])
    op=''.join(ip)
    import re
    op=re.sub(r'(零.)零.','',op) #正则表达式处理连续零
    op=re.sub(r'(零[拾佰仟萬亿])','零',op)
    rt= list(op)
    if rt[-1]=='拾' :
        rt.pop(-1)
    return ''.join(rt)

def thousandFormat(ip): #千分格式化 #ip为要转换的数字
    if not isinstance(ip, str):
        ip=str(ip)
    list_str=list(ip) #get input num list 
    for i in range(1,int(len(list_str)/2)):
        list_str.insert(-i*3-i+1,',') #insert ','
    if list_str[0]==',':
        list_str.pop(0)
    return ''.join(list_str)

def printChinese(ip): #ip为要转换的数字
    if not isinstance(ip, str):
        ip=str(ip)
    list_str=list(ip) #get input num list 
    out_put=[]
    char_map={'0':'零','1':'壹','2':'貳','3':'叁','4':'肆','5':'伍','6':'陆','7':'柒','8':'捌','9':'玖'}
    it=['萬','亿']
    for i in list_str:
        out_put.append(char_map[i]) #得到中文大写
    ot=''
    for i in range(1,int(len(list_str)/4)+1):
        if i==1:
            ot=wan(out_put[-4:len(out_put)])
        else:
            ot=wan(out_put[-i*4:-i*4+4])+it[i%2]+ot
    if len(list_str)%4!=0:
        ot=wan(out_put[0:len(list_str)%4])+it[(int(len(list_str)/4)+1)%2]+ot
    return ot
input_=input()
print(thousandFormat(input_),printChinese(input_))

发表于 2021-01-23 23:20:55 回复(0)