Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
这题纯粹考细心,其他没什么说的
const string onedigit[9] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
const string teensless20[10] = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
const string teens[8] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
class Solution {
string get_digit(int num)
{
return onedigit[num-1];
}
string get_teens(int num)
{
if (num < 20)
return teensless20[num - 10];
return teens[num / 10 - 2];
}
string get_hundred(int num)
{
string re;
if (num >= 100)
re += get_digit(num / 100) + " Hundred ";
if (num - num / 100 * 100>=10)
re +=get_teens(num - num / 100 * 100)+" ";
if (num % 10 != 0 && (num - num / 100 * 100 >= 20 || num - num / 100 * 100<10))
re += get_digit(num % 10);
while (re.back() == ' ')
re.pop_back();
return re;
}
public:
string numberToWords(int num) {//0-2 147 483 647
if (num == 0)
return "Zero";
string re;
vector<int>digits;
while (num != 0)
{
digits.push_back(num % 10);
num /= 10;
}
if (digits.size() > 9)
re += get_digit(digits[9])+" Billion ";
if (digits.size() > 6)
{
int jmax = digits.size() >= 9 ? 8 : digits.size()-1;
int sum = 0;
for (int j = jmax; j >= 6; j--)
sum = 10 * sum + digits[j];
if (sum>0)
re += get_hundred(sum)+" Million ";
}
if (digits.size() > 3)
{
int jmax = digits.size() >= 6 ? 5 : digits.size()-1;
int sum = 0;
for (int j = jmax; j >= 3; j--)
sum = 10 * sum + digits[j];
if (sum>0)
re += get_hundred(sum) + " Thousand ";
}
int jmax = digits.size() >= 3 ? 2 : digits.size()-1;
int sum = 0;
for (int j = jmax; j >= 0; j--)
sum = 10 * sum + digits[j];
if (sum>0)
re += get_hundred(sum);
while (re.back() == ' ')
re.pop_back();
return re;
}
};
accepted