# 273. Integer to English Words
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 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
Approach 1: Segment (every three digits) by segment.
# Code (Python)
Approach 1:
# Code (C++)
Approach 1:
class Solution {
private:
string getSeg(int num) {
string d00_19[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
string d20_90[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
ostringstream oss;
// hundreds
int hundreds = num / 100;
if (hundreds > 0)
oss << " " << d00_19[hundreds] << " Hundred";
// tens
int tens = num % 100;
if (tens > 0 && tens < 20)
oss << " " << d00_19[tens];
else if (tens >= 20)
{
int digit = num % 10;
oss << " " << d20_90[(tens-digit)/10];
if (digit > 0)
oss << " " << d00_19[digit];
}
return oss.str();
}
public:
string numberToWords(int num) {
if (num == 0)
return "Zero";
string units[] = {"", " Thousand", " Million", " Billion"};
string res = "";
for (int i = 0; i < 4 && num; ++i)
{
string seg = getSeg(num % 1000);
if (seg.size() > 0)
res = seg + units[i] + res;
num /= 1000;
}
return res.substr(1);
}
};