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"
思路:
这种题是非常需要注意细节的题目,尤其是空格之类的分割符,另外,因为我们按照Thousand,Million,Billion进行分割,所以我们可以写一个函数用于处理Thousand以内的情况,代码如下:
class Solution {
public:
Solution() {
num_string[1] = "One";
num_string[2] = "Two";
num_string[3] = "Three";
num_string[4] = "Four";
num_string[5] = "Five";
num_string[6] = "Six";
num_string[7] = "Seven";
num_string[8] = "Eight";
num_string[9] = "Nine";
num_string[10] = "Ten";
num_string[11] = "Eleven";
num_string[12] = "Twelve";
num_string[13] = "Thirteen";
num_string[14] = "Fourteen";
num_string[15] = "Fifteen";
num_string[16] = "Sixteen";
num_string[17] = "Seventeen";
num_string[18] = "Eighteen";
num_string[19] = "Nineteen";
num_string[20] = "Twenty";
num_string[30] = "Thirty";
num_string[40] = "Forty";
num_string[50] = "Fifty";
num_string[60] = "Sixty";
num_string[70] = "Seventy";
num_string[80] = "Eighty";
num_string[90] = "Ninety";
}
string numberToWords(int num) {
if (num == 0) return "Zero";
string res;
int m = num / 1E9;
if (m > 0) res += getOneClass(m) + " Billion";
num -= m * 1E9;
m = num / 1E6;
if (m > 0) res += res.empty() ? getOneClass(m) + " Million": " " + getOneClass(m) + " Million";
num -= m * 1E6;
m = num / 1E3;
if (m > 0) res += res.empty() ? getOneClass(m) + " Thousand": " " + getOneClass(m) + " Thousand";
num -= m * 1E3;
if (num > 0) res += res.empty() ? getOneClass(num) : " " + getOneClass(num);
return res;
}
private:
unordered_map<int, string> num_string;
string getOneClass(int n) {
string res;
int m = n / 100;
if (m > 0) res += num_string[m] + " Hundred";
n -= m * 100;
m = n / 10;
if (m == 1) res += res.empty() ? num_string[n] : " " + num_string[n];
else if (m > 1){
res += res.empty() ? num_string[m * 10] : " " + num_string[m * 10];
n -= m * 10;
if (n > 0) res += res.empty() ? num_string[n] : " " + num_string[n];
}
else if(m == 0){
if(n>0) res += res.empty() ? num_string[n] : " " + num_string[n];
}
return res;
}
};