Convert Digits/Numbers to Words
The problem
You are given a non-negative integer num with at most 4 digits (0 <= num <= 9999). Your task is to convert this number into its English words representation.
**Input: **num = 7824 Output: "seven thousand eight hundred twenty four" **Explanation: **7824 is read as "seven thousand eight hundred twenty four"
Input: num = 370 **Output: **"three hundred seventy" Explanation: 370 is read as "three hundred seventy"
Input: num = 1001
- 0 <= num <= 9999
- Do not include "and" between words (e.g., write "one hundred one", not "one hundred and one")
- The output should be all lowercase with single spaces between words
cpp
class Solution {
public:
string numberToWords(int num) {
// Your code goes here
}
};java
class Solution {
public String numberToWords(int num) {
// Your code goes here
}
}python
class Solution:
def numberToWords(self, num: int) -> str:
# Your code goes herejavascript
class Solution {
numberToWords(num) {
// Your code goes here
}
}csharp
class Solution {
public string NumberToWords(int num) {
// Your code goes here
}
}go
func numberToWords(num int) string {
}Stuck? Show a way to structure it+
- 01Return zero immediately for input 0.
- 02Split the number into thousands, hundreds, tens, and ones.
- 03Use lookup tables for values below 20 and for tens multiples.
- 04Append only nonzero groups with single-space joining.
Reference answer
Then expect these follow-ups
How would you extend this to arbitrary 32-bit integers?
Tests: scalable decomposition
How would you parse English words back into a number?
Tests: stateful parsing
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question