Home > Article > Backend Development > . Integer to English Words
273. Integer to English Words
Hard
Topics : Math, String, Recursion
Convert a non-negative integer num to its English words representation.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
To solve this problem, we can follow these steps:
Define the words for numbers: We need arrays for the words representing single digits, teens, tens, and the thousands groupings.
Create a helper function: This function will handle numbers less than 1000, converting them to English words.
Recursive function: The main function will recursively process chunks of the number, adding the appropriate thousand group label (e.g., Thousand, Million, Billion).
Edge cases: Handle edge cases like 0 and numbers where intermediate chunks are zero.
Let's implement this solution in PHP: 273. Integer to English Words
Explanation:
Main Function (numberToWords):
- Checks if the input number is 0 and returns "Zero".
- Initializes the thousands array with the labels for a thousand groupings.
- Iteratively processes the number in chunks of thousands, using the helper function to convert each chunk to words.
- Constructs the final result string by combining the words for each chunk with the appropriate thousand group label.
Helper Function (helper):
- Uses predefined arrays for numbers below 20 and for the tens multiples.
- Recursively constructs the English words for numbers less than 1000:
- For numbers less than 20, directly returns the corresponding word.
- For numbers less than 100, combines the word for the tens place with the result of a recursive call for the units place.
- For numbers 100 and above, combines the word for the hundreds place with the result of a recursive call for the remainder.
This solution handles the constraints and edge cases effectively, providing the correct English words representation for any number within the given range.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Integer to English Words. For more information, please follow other related articles on the PHP Chinese website!