The solution converts a given integer to its English words representation. It uses a dictionary to map numbers to their English counterparts for single digits, two digits, and multiples of ten. The algorithm handles the integer in chunks of three digits, corresponding to the place values like Thousand, Million, etc. These chunks are processed from right to left, adjusting for place value. Special attention is given to numbers like '100' or '110' where 'Zero' needs to be managed correctly to avoid incorrect outputs like 'Zero Hundred'. The final English representation is then constructed by reversing the order of processed chunks and concatenating them with appropriate place values.
时间复杂度: O(n)
空间复杂度: O(n)
class Solution:
def numberToWords(self, num: int) -> str:
# Dictionary for number to word conversion
num_dict = {'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four', '5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine', '10': 'Ten', '11': 'Eleven', '12': 'Twelve', '13': 'Thirteen', '14': 'Fourteen', '15': 'Fifteen', '16': 'Sixteen', '17': 'Seventeen', '18': 'Eighteen', '19': 'Nineteen', '20': 'Twenty', '30': 'Thirty', '40': 'Forty', '50': 'Fifty', '60': 'Sixty', '70': 'Seventy', '80': 'Eighty', '90': 'Ninety'}
# Place value names by chunk index
num_count = {1: 'Thousand', 2: 'Million', 3: 'Billion', 4: 'Trillion'}
# Handle zero explicitly
if num == 0:
return 'Zero'
# General case
count = 0
output = []
num_str = str(num)
n = len(num_str)
str_list = []
index = len(num_str) - 1
while index >= 0:
temp = []
if index >= 2:
temp.append(num_str[index - 2])
if index >= 1:
temp.append(num_str[index - 1])
temp.append(num_str[index])
str_list.append(''.join(temp))
index -= 3
for triplet in str_list:
temp = ''
if len(triplet) == 3:
if triplet[0] != '0':
temp += num_dict[triplet[0]] + ' Hundred '
if triplet[1] != '0':
if triplet[1] + triplet[2] in num_dict:
temp += num_dict[triplet[1] + triplet[2]]
else:
temp += num_dict[triplet[1] + '0'] + ' ' + num_dict[triplet[2]]
else:
if triplet[2] != '0':
temp += num_dict[triplet[2]]
else:
if triplet[1] != '0':
if triplet[1] + triplet[2] in num_dict:
temp += num_dict[triplet[1] + triplet[2]]
else:
temp += num_dict[triplet[1] + '0'] + ' ' + num_dict[triplet[2]]
else:
if triplet[2] != '0':
temp += num_dict[triplet[2]]
if len(triplet) <= 2:
if triplet in num_dict:
temp += num_dict[triplet]
else:
temp += num_dict[triplet[0] + '0'] + ' ' + num_dict[triplet[1]]
output.append(temp)
result = [output[0]]
for i in range(len(output) - 1):
result.append(num_count[i + 1])
result.append(output[i + 1])
result.reverse()
index = 0
while index < len(result):
if result[index] == 'Zero':
if index == len(result) - 1:
result.pop(index)
else:
result.pop(index)
result.pop(index)
else:
index += 1
return ' '.join(result)