题目链接:https://leetcode-cn.com/problems/integer-to-english-words/comments/
题目描述
将非负整数转换为其对应的英文表示。可以保证给定输入小于 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 难度判断很迷,某些简单题反而做得一头包。
- 这道题主要是要处理各种边界情况比较多一些,另外存英文单词用数组就行,我多此一举用了map,败笔。
- 思路非常简单,将整数从低位到高位三三分开,分别判断就行。
代码如下:
class Solution {
public:
string three_numberToWords(int num){
string en_num = "";
unordered_map<int, string> en_num1 = {{0, ""}, {1, " One"}, {2, " Two"}, {3, " Three"}, {4, " Four"}, {5, " Five"}, {6, " Six"}, {7, " Seven"}, {8, " Eight"}, {9, " Nine"}, {10, " Ten"}, {11, " Eleven"}, {12, " Twelve"} ,{13, " Thirteen"} ,{14, " Fourteen"} ,{15, " Fifteen"} ,{16, " Sixteen"} ,{17, " Seventeen"} ,{18, " Eighteen"} ,{19, " Nineteen"}};
unordered_map<int, string> en_num2 = {{0, ""}, {2, " Twenty"}, {3, " Thirty"}, {4, " Forty"}, {5, " Fifty"}, {6, " Sixty"}, {7, " Seventy"}, {8, " Eighty"}, {9, " Ninety"}};
if(num < 20) return en_num1[num];
if(num >= 20 && num < 100){
return en_num2[num/10] + en_num1[num%10];
}
if(num >= 100 && num%100 >= 20){
return en_num1[num/100] + " Hundred" + en_num2[num%100/10] + en_num1[num%100%10];
}
if(num >= 100 && num%100 < 20){
return en_num1[num/100] + " Hundred" + en_num1[num%100];
}
return "";
}
string numberToWords(int num) {
string res;
if(num == 0) return "Zero";
int billon = num / 1000000000;
int milion = num % 1000000000 / 1000000;
int thousand = num % 1000000000 % 1000000 / 1000;
int simple = num % 1000000000 % 1000000 % 1000;
if(billon != 0) res += three_numberToWords(billon) + " Billion";
if(milion != 0) res += three_numberToWords(milion) + " Million";
if(thousand != 0) res += three_numberToWords(thousand) + " Thousand";
if(simple != 0) res += three_numberToWords(simple);
while(res[res.size() - 1] == ' ') res.erase(res.end()-1);
while(res[0] == ' ') res.erase(res.begin());
return res;
}
};