Convert a non-negative integer num
to its English words representation.
For example:
num = 123
, the output should be "One Hundred Twenty Three"
num = 12345
, the output should be "Twelve Thousand Three Hundred Forty Five"
num = 1234567
, the output should be "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Write a function that takes a non-negative integer as input and returns its English words representation. The input number will be between 0 and 231 - 1.
class Solution:
def numberToWords(self, num: int) -> str:
less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
def helper(n):
if n < 20:
return less_than_20[n]
elif n < 100:
return tens[n // 10] + (" " + less_than_20[n % 10]) if n % 10 else tens[n // 10]
else:
return less_than_20[n // 100] + " Hundred " + helper(n % 100)
if num == 0:
return "Zero"
result = []
for i in range(4):
if num % 1000 != 0:
result.append(helper(num % 1000) + " " + thousands[i])
num //= 1000
return " ".join(result[::-1]).strip()
The solution converts a non-negative integer into its English words representation. It uses helper arrays to store the string representations of numbers less than 20, tens, and thousands. The helper
function converts numbers less than 1000 into words. The main function iterates through the number in chunks of 1000, converting each chunk into words and appending the appropriate magnitude (thousand, million, billion).
solution = Solution()
print(solution.numberToWords(123)) # Output: One Hundred Twenty Three
print(solution.numberToWords(12345)) # Output: Twelve Thousand Three Hundred Forty Five
print(solution.numberToWords(1234567)) # Output: One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
A naive solution would involve using a large number of if
and elif
statements to handle each possible number range. This would be very verbose and difficult to maintain.
The provided solution is an optimal solution as it breaks down the problem into smaller subproblems that can be solved recursively. This makes the code more readable and easier to maintain.
The time complexity is O(1) because the input number is at most 2^31 - 1, meaning the loop in the numberToWords
function iterates at most 4 times, and the helper
function also takes constant time as it deals with numbers less than 1000.
The space complexity is O(1) because the space used by the less_than_20
, tens
, and thousands
arrays is constant, regardless of the input number.
less_than_20
array.tens
array and the less_than_20
array.less_than_20
array and the helper
function.