您的位置:首页 > 其它

[LeetCode] Integer to English Words

2015-08-31 12:18 337 查看
Integer to English Words

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"


Hint:

Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.

Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.

There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

一定要考虑各种边界情况。正如提示里所说的。

class Solution {
public:
string getWord(int num, string *digit, string *digit1) {
if (num == 0) return "Zero";
string res;
int h = num / 100;
num %= 100;
if (h > 0) res += digit[h] + " Hundred";
if (num == 0) return res;
else if (h > 0) res += " ";
if (num < 20) {
res += digit[num];
} else {
h = num / 10;
num %= 10;
res += digit1[h];
if (num != 0) res += " " + digit[num];
}
return res;
}
string numberToWords(int num) {
if (num == 0) return "Zero";
string digit[20] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
string digit1[10] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string digit2[10] = {"", "Thousand", "Million", "Billion"};
vector<string> words;
string str;
int num2, cnt = 0;
while (num != 0) {
num2 = num % 1000;
str = getWord(num2, digit, digit1);
if (str != "Zero") {
if (cnt > 0) words.push_back(str + " " + digit2[cnt]);
else words.push_back(str);
}
num /= 1000;
++cnt;
}
string res;
for (int i = (int)words.size() - 1; i > 0; --i) {
res += words[i] + " ";
}
res += words.front();
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: