問題描述:
銀行在打印票據的時候,常常需要將阿拉伯數字表示的人民幣金額轉換為大寫表示,現在請你來完成這樣一個程序。
在中文大寫方式中,0到10以及100、1000、10000被依次表示為: 零 壹 貳 叄 肆 伍 陸 柒 捌 玖 拾 佰 仟 萬
以下的例子示范了阿拉伯數字到人民幣大寫的轉換規則:
1 壹圓
11 壹拾壹圓
111 壹佰壹拾壹圓
101 壹佰零壹圓
-1000 負壹仟圓
1234567 壹佰貳拾叄萬肆仟伍佰陸拾柒圓
現在給你一個整數a(|a|<100000000), 請你打印出人民幣大寫表示.
例如:a=1
則輸出:壹圓
注意:請以Unicode的形式輸出答案。提示:所有的中文字符,在代碼中直接使用其Unicode的形式即可滿足要求,中文的Unicode編碼可以通過如下方式獲得:u'壹'。
這題目最頭疼的地方是當一串數字中間和末尾都存在0的時候,要去掉重復出現的0和對應的單位。
例如: 6100 0310元
對應的大寫為: 陸仟壹佰萬零叄佰壹拾圓
這里6100后面的零轉換成大寫之后都去掉了,0310個位數上的0也去掉了,但是千位上的數字0保留。

1 num_dic = {'0':u'零', '1':u'壹', '2':u'貳', '3':u'叄', '4':u'肆', '5':u'伍', '6':u'陸', '7':u'柒', '8':u'捌', '9':u'玖'} 2 unit_dic = {0:u'仟', 1:'佰', 2:'拾', 3:'萬', 4:'仟', 5:'佰', 6:'拾', 7:''} 3 decimal_dic={0:u'角',1:u'分',2:u'厘',3:u'毫'} 4 def convert_int(num): 5 temp = [] 6 t = str('%8d'%abs(num)) #重點:把數字換成固定長度8位的字符串 7 for s in range(0,4): 8 if t[s] != ' ' and t[s] != '0': 9 temp.append(num_dic[t[s]]) 10 temp.append(unit_dic[s]) 11 if t[s] == '0' and s <3 and t[s+1] != '0': 12 temp.append(num_dic[t[s]]) 13 if(t[2] != ' ' and t[3] == '0'): 14 temp.append('萬') 15 for s in range(4,8): 16 if t[s] != ' ' and t[s] != '0': 17 temp.append(num_dic[t[s]]) 18 temp.append(unit_dic[s]) 19 if t[s] == '0' and s < 7 and t[s+1] != '0': 20 temp.append(num_dic[t[s]]) 21 temp = ''.join(temp) 22 if num < 0: 23 temp = '負' + temp 24 if num == 0: 25 temp = '零' + temp 26 27 return temp + u'圓' 28 29 def convert_decimal(num): 30 t = str('%4d'%num) 31 temp = [] 32 for s in range(0,4): 33 if t[s] != ' ' and t[s] != '0': 34 temp.append(num_dic[t[s]]) 35 temp.append(decimal_dic[s]) 36 if t[s] == '0' and s < 3 and t[s + 1] != '0': 37 temp.append(num_dic[t[s]]) 38 temp = ''.join(temp) 39 if len(temp) == 0: 40 return '整' 41 return temp 42 43 def convert_money(money): 44 num = round(float(money),4) 45 integer,decimal = str(num).split('.') 46 result_int = convert_int(int(integer)) 47 result_decimal = convert_decimal(int(decimal)) 48 return result_int+result_decimal 49 50 money = input('請輸入轉換的金額:') 51 print(convert_money(money))