题目:
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"
代码:
方法一——自己的方法比较乱:
class Solution {
public:
vector<string> s1 = { "Thousand","Million","Billion" };
vector<string> tens = {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
vector<string> tys = {"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
vector<string> ones = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
string numberToWords(int num) {
if (num == 0)return "Zero";
string res = "";
if (num < 1000) {
int h = num / 100;
if (h > 0) {
res += ones[h - 1] + " Hundred ";
}
num = num % 100;
if(num>0){
h = num / 10;
if (h > 1) {
res += tys[h - 2];
num = num % 10;
if (num > 0) {
res += " " + ones[num % 10 - 1];
}
}
else if (h == 1) {
res += tens[num - 10];
}
else {
res += ones[num - 1];
}}
}
else {
int i = 0;
while (num > 0) {
int temp1 = num % 1000;
int temp2 = num / 1000;
string temp = numberToWords(temp1);
if (temp != "Zero") {
res.insert(0, temp + " ");
}
if (temp2 != 0&&temp2%1000!=0) {
res.insert(0, s1[i] + " ");
}
num = temp2;
i++;
}
}
res.erase(res.find_last_not_of(" ") + 1);
return res;
}
};
方法二——别人的方法,比较有思路有条理:
class Solution {
public:
string numberToWords(int num) {
string res = convertHundred(num % 1000);
vector<string> v = {"Thousand", "Million", "Billion"};
for (int i = 0; i < 3; ++i) {
num /= 1000;
res = num % 1000 ? convertHundred(num % 1000) + " " + v[i] + " " + res : res;
}
while (res.back() == ' ') res.pop_back();
return res.empty() ? "Zero" : res;
}
string convertHundred(int num) {
vector<string> v1 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> v2 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string res;
int a = num / 100, b = num % 100, c = num % 10;
res = b < 20 ? v1[b] : v2[b / 10] + (c ? " " + v1[c] : "");
if (a > 0) res = v1[a] + " Hundred" + (b ? " " + res : "");
return res;
}
};