题目
给定一个整数,打印该整数的英文描述。
示例 1:
输入: 123
输出: “One Hundred Twenty Three”
示例 2:
输入: 12345
输出: “Twelve Thousand Three Hundred Forty Five”
示例 3:
输入: 1234567
输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
示例 4:
输入: 1234567891
输出: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”
解题思路
- 3 3 3 个一组分开求数值大小。注意:特殊处理 0 0 0 - 20 20 20,还有 100 100 100 也需要注意 。
- i n t int int 数字最大 10 10 10 位到 2 2 2 m i l l i o n million million。
代码
class Solution {
public:
string numberToWords(int num) {
if(num == 0){
return "Zero";
}
//先将负数变为正数
long n = num;
string ans = "";
if(n < 0){
n = -num;
ans += "Negative";
}
//找三次
string str[4] = {"Billion", "Million", "Thousand", ""};
int t = 1000000000;
for(int i = 0; i < 4; ++i){
cout << n / t << endl;
string temp = getThreeNum(n / t);
n %= t;
t /= 1000;
if(temp != ""){
if(ans != ""){
ans += " ";
}
ans += temp;
if(str[i] != ""){
ans += " ";
}
ans += str[i];
}
}
return ans;
}
string number[21] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"};
string numTen[10] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string getThreeNum(int num){
if(num == 0){
return "";
}
string ans = "";
if(num / 100 != 0){
ans += number[num / 100];
ans += " ";
ans += "Hundred";
num %= 100;
}
if(num == 0){
return ans;
}
if(num <= 20){
if(ans != ""){
ans += " ";
}
ans += number[num];
}
else{
if(ans != ""){
ans += " ";
}
ans += numTen[num / 10];
num %= 10;
if(num != 0){
ans += " ";
ans += number[num];
}
}
return ans;
}
};