题目描述:
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"解题思路:
分段处理,把输入数值分别按照十亿(Billion,1000000000),百万(Million,1000000),千(Thousand,1000)进行处理
AC代码如下:
class Solution {
public:
string numberToWords(int num) {
if (num == 0) return string("Zero");
vector<int> chunk = { 1000000000, 1000000, 1000, 1 };
vector<string> name = { " Billion", " Million", " Thousand", "" };
string ans;
for (int i = 0; i < chunk.size(); ++i){
if (num / chunk[i]){
if (ans != "") ans += " ";
ans += num2word(num / chunk[i]) + name[i];
num = num%chunk[i];
}
}
return ans;
}
string num2word(int num){
vector<string> words1 = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
vector<string> words2 = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
vector<string> words3 = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
string res;
if (num / 100){
int idx = num / 100;
num = num % 100;
res += words1[idx] + " Hundred";
}
if (num / 10){
if (num / 10 == 1){
int idx = num % 10;
if (res != "") res += " ";
res += words2[idx];
return res;
}
else{
int idx = num / 10;
if (res != "") res += " ";
res += words3[idx];
num = num % 10;
}
}
if (num){
int idx = num;
if (res != "") res += " ";
res += words1[idx];
}
return res;
}
};