【LeetCode】273. Integer to English Words

时间:2022-02-20 17:15:26

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"

Show Hint

 先把数字分割成4个三分位处理。前3个三分位分别加上Billion,Million,Thousand。
三分位处理函数为Helper()
class Solution {
public:
string Helper(string numStr, string dict1[], string dict2[], string dict3[])
{
int num = atoi(numStr.c_str());
if(num == )
return "";
else
{
string ret = "";
int hundred = numStr[] - '';
int ten = numStr[] - '';
int one = numStr[] - ''; if(hundred != )
ret += dict1[hundred-] + " Hundred"; if(ten == )
{
if(one == )
return ret;
else
return (ret=="")?(dict1[one-]):(ret+" "+dict1[one-]);
}
else if(ten == )
{
return (ret=="")?(dict2[one]):(ret+" "+dict2[one]);
}
else
{
if(one == )
return (ret=="")?(dict3[ten-]):(ret+" "+dict3[ten-]);
else
return (ret=="")?(dict3[ten-]+" "+dict1[one-]):(ret+" "+dict3[ten-]+" "+dict1[one-]);
}
}
}
string numberToWords(int num) {
if(num == )
return "Zero";
else
{
string ret = "";
string dict1[] = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
string dict2[] = {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen",
"Eighteen","Nineteen"};
string dict3[] = {"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; string numStr = to_string(num);
int len = numStr.size();
string padding = string(-len, '');
numStr = padding + numStr; string billionStr = Helper(numStr.substr(,), dict1, dict2, dict3);
if(billionStr != "")
ret += billionStr + " Billion"; string millionStr = Helper(numStr.substr(,), dict1, dict2, dict3);
if(millionStr != "")
ret += (ret=="")?(millionStr+" Million"):(" "+millionStr+" Million"); string thousandStr = Helper(numStr.substr(,), dict1, dict2, dict3);
if(thousandStr != "")
ret += (ret=="")?(thousandStr+" Thousand"):(" "+thousandStr+" Thousand"); string oneStr = Helper(numStr.substr(,), dict1, dict2, dict3);
if(oneStr != "")
ret += (ret=="")?(oneStr):(" "+oneStr);
return ret;
}
}
};

【LeetCode】273. Integer to English Words