问题描述:
将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
示例 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"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-to-english-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果:
代码描述:
思路:0,1-9,10-19, 20 - 90,100,1000 ,百万,十亿 的翻译。先准备好。不然这个题没法做。
单独写一个函数,用自身调用,是因为如果有num == 0的情况,需要特殊处理。
最后需要去掉空格,有且仅有1个空格,用迭代器,不要用索引,因为索引再删除的时候会出现越界错误。
这道题,把 if else 用到了极致!
class Solution {
public:
string numberToWords(int num) {
return num == 0? "Zero" : translate(num);
}
string translate(int num)
{
string n1[10]={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
string n2[10] = {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
string n3[10]={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
string s;
if(num < 10)
s = n1[num];
else if(num < 20)
s = n2[num%10];
else if(num < 100)
s = n3[num/10] + " " + n1[num%10];
else if(num < 1000)
s = translate(num/100) + " Hundred " + translate(num%100);
else if(num < 1000000)
s = translate(num/1000) + " Thousand " + translate(num%1000);
else if(num < 1000000000)
s = translate(num/1000000) + " Million " + translate(num%1000000);
else
s = translate(num/1000000000) + " Billion " + translate(num%1000000000);
if(s[s.size()-1] == ' ')
s.erase(s.end()-1);
return s;
}
};