273. Integer to English Words
Problem description:
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.
Example 1:
Input: 123
Output: “One Hundred Twenty Three”
Example 2:
Input: 12345
Output: “Twelve Thousand Three Hundred Forty Five”
Example 3:
Input: 1234567
Output: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
Example 4:
Input: 1234567891
Output: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”
Solution:
Question can ask in interview:
- What format is the integer? contain dots? floating number?
- Input type, integer/string
- Output type, should be string
- time/space complexity restriction
The hint from this question, Group the number by thousands (3 digits). Write a helper function that takes a number less than 1000 and convert just that chunk to words.
use some example to demonstrate how to set up the array.
1~19, all different words
20~99, different words too
100~999, can be constructed by previous two with"Hundred"
.
greater than 1000, can use previous three with"Thousand", "Million", "Billion"
.After creating the dictionary, we can try to divide the question into smaller pieces. Since the result with
num
greater than 1000 are similar, we can use a helper function to construct strings less than 1000.Dealing with
num
greater than thousands. The pattern is to dividenum
with 1000 multiple times and counting how many 1000 we have divided.
1 | class Solution: |
1 | class Solution { |
time complexity: $O(1)$, because the length of num
is limited and the loop will be called constant number of times.