/*按照提示,将原来数字分成3个一组,每个组内数字字符串化,然后再组合起来。*/
class Solution {
public:
string numberToWords(int num) {
string units[4] = {"", " Thousand", " Million", " Billion"};
int i = 0;
string res;
while(num != 0){
int n = num % 1000;
if(n > 0) res = words(n) + units[i] + (res.empty() ? "" : " " + res);
num = num / 1000;
++i;
}
return res.empty() ? "Zero" : res;
}
string words(int num){
string res;
string gewei[10] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
string shiwei[10] = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string shiji[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
int n = num / 100;
if(n > 0){
res = res + gewei[n] + " Hundred";
}
n = num % 100;
if(n >= 10 && n < 20){
if(!res.empty()) res += " ";
res = res + shiji[n-10];
return res;
}
else if(n >= 20){
n = n / 10;
if(!res.empty()) res += " ";
res = res + shiwei[n-1];
}
n = num % 10;
if(n > 0){
if(!res.empty()) res += " ";
res += gewei[n];
}
return res;
}
};
LeetCode之Integer to English Words
最新推荐文章于 2022-03-25 19:34:53 发布