整形转中文
实现一个整形转中文的函数.
输入:
10023450
输出:
一千零二万三千四百五十
要求:
1. 可用中文"个","十","百","千","万","亿","兆","零","负"
2. 最大支持百兆
1,000,000,000,000,000
^ ^ ^
兆 亿 万
思路:
1.每4位拆分成一段(个十百千)(万亿兆)
2.中间的"零", 若重叠, 只输出一个"零", 如1004 -> 一千零四
3.末尾中的"零"不输出, 如1100 -> 一千一百
4.支持百兆, 输入要用long long
class Solution(): def intToChinese(self, num): if len(str(num)) > 15: return 'too long' #初始化 result_array, flag = [], '' if str(num)[0] == '-': num_array = list(str(num))[1: ][:: -1] flag = '负' else: num_array = list(str(num))[:: -1] dict_help = {'0': '零', '1' : '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'} directions = ['十', '百', '千'] #长度为1 if len(num_array) == 1: return dict_help[num_array[0]] #长度 > 1 for i in range(len(num_array)): #针对千,百,十,个 if i == 0 and num_array[i] != '0': result_array.append(dict_help[num_array[i]]) elif 1 <= i <= 3: if num_array[i] == '0': result_array.insert(0, '零') else: result_array.insert(0, dict_help[num_array[i]] + directions[i - 1]) if num_array[i] != '0' else result_array.insert(0, '零') if 4 <= i < 8: if i == 4: res = self.help(num_array[4: 8], '万', dict_help, directions) result_array = res + result_array if 8 <= i < 12: if i == 8: res = self.help(num_array[8: 12], '亿', dict_help, directions) result_array = res + result_array if i >= 12: if i == 12: res = self.help(num_array[12: ], '兆', dict_help, directions) result_array = res + result_array results = self.removeZero(result_array) #如果存在连续的0的话,则剔除 return flag + ''.join(results) def removeZero(self, nums): new_nums = [] for i in range(len(nums)): if nums[i - 1] == '零' and nums[i] == '零': continue else: new_nums.append(nums[i]) if new_nums[-1] == '零': new_nums.remove(nums[-1]) return new_nums #针对万,亿,兆 def help(self, nums, name, dict_help, directions): res = [] for i in range(len(nums)): if i == 0: if nums[i] != '0': res.append(dict_help[nums[i]] + name) else: res.append('零') else: if nums[i] != '0': if name not in res[0]: res.append(dict_help[nums[i]] + directions[i - 1] + name) else: res.append(dict_help[nums[i]] + directions[i - 1]) else: res.append('零') return res[:: -1] result = Solution().intToChinese(10000310023450) print(result)