273. Integer to English Words
Convert a non-negative integer num to its English words representation.
Example 1:
Input: num = 123
Output: “One Hundred Twenty Three”
Example 2:
Input: num = 12345
Output: “Twelve Thousand Three Hundred Forty Five”
Example 3:
Input: num = 1234567
Output: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
Constraints:
- 0 < = n u m < = 2 31 − 1 0 <= num <= 2^{31} - 1 0<=num<=231−1
From: LeetCode
Link: 273. Integer to English Words
Solution:
Ideas:
1. Arrays for Words:
- below_20: Words for numbers from 0 to 19.
- tens: Words for multiples of ten (20, 30, …, 90).
- thousands: Words for large numbers (thousand, million, billion).
2. Helper Function:
- The helper function recursively converts numbers less than 1000 to words.
3. Main Conversion Function:
- The numberToWords function handles the division of the number into thousands, millions, etc.
- It concatenates the results from the helper function with the appropriate thousand, million, or billion labels.
- It ensures there are no trailing spaces in the final result.
4. Memory Management:
- The result is stored in a dynamically allocated string. Don’t forget to free the allocated memory after use.
Code:
const char* below_20[] = {
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"
};
const char* tens[] = {
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
const char* thousands[] = {
"", "Thousand", "Million", "Billion"
};
void helper(int num, char* result) {
if (num == 0) return;
if (num < 20) {
strcat(result, below_20[num]);
strcat(result, " ");
} else if (num < 100) {
strcat(result, tens[num / 10]);
strcat(result, " ");
helper(num % 10, result);
} else if (num < 1000) {
helper(num / 100, result);
strcat(result, "Hundred ");
helper(num % 100, result);
}
}
char* numberToWords(int num) {
if (num == 0) {
char* result = (char*)malloc(5 * sizeof(char));
strcpy(result, "Zero");
return result;
}
char* result = (char*)malloc(1024 * sizeof(char)); // Allocating enough space for the result
result[0] = '\0'; // Initializing the result string
int i = 0;
while (num > 0) {
if (num % 1000 != 0) {
char temp[1024] = "";
helper(num % 1000, temp);
if (strlen(thousands[i]) > 0) {
strcat(temp, thousands[i]);
strcat(temp, " ");
}
strcat(temp, result);
strcpy(result, temp);
}
num /= 1000;
i++;
}
// Remove trailing space
int len = strlen(result);
if (len > 0 && result[len - 1] == ' ') {
result[len - 1] = '\0';
}
return result;
}