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"
Hint:
- Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
- Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
- There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
这道题是给出数字的读法,题目难度为Medium。
题目本身不难,但是比较繁琐,0-9、10-19、以及10的整数倍的读法都不同,要逐个列出来。题目中要注意判断的一点是前面是否已经有数字,即当前要读的数字是否是第一个,如果不是第一个要在读之前加上空格,如果是第一个则不需要。最后如果数字是0,也要特殊处理。另外题目中的读法是没有“and”的。具体代码:
class Solution {
string helper1(int num) {
switch(num) {
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
default: return "";
}
}
string helper2(int num) {
switch(num) {
case 2: return "Twenty";
case 3: return "Thirty";
case 4: return "Forty";
case 5: return "Fifty";
case 6: return "Sixty";
case 7: return "Seventy";
case 8: return "Eighty";
case 9: return "Ninety";
default: return "";
}
}
string helper3(int num) {
switch(num) {
case 10: return "Ten";
case 11: return "Eleven";
case 12: return "Twelve";
case 13: return "Thirteen";
case 14: return "Fourteen";
case 15: return "Fifteen";
case 16: return "Sixteen";
case 17: return "Seventeen";
case 18: return "Eighteen";
case 19: return "Nineteen";
default: return "";
}
}
string cvtChunk(int num) {
string rst;
bool isFirstNonZero = true;
if(num >= 100) {
rst += helper1(num/100);
rst += " Hundred";
isFirstNonZero = false;
}
if(num%100/10 == 1) {
if(!isFirstNonZero) rst += " ";
rst += helper3(num%100);
}
else {
if(num%100/10 > 1) {
if(!isFirstNonZero) rst += " ";
rst += helper2(num%100/10);
isFirstNonZero = false;
}
if(!isFirstNonZero && num%10>0) rst += " ";
rst += helper1(num%10);
}
return rst;
}
public:
string numberToWords(int num) {
string rst;
bool isFirstNonZero = true;
if(num >= 1000000000) {
rst += cvtChunk(num/1000000000);
rst += " Billion";
isFirstNonZero = false;
}
if(num%1000000000/1000000) {
if(!isFirstNonZero) rst += " ";
rst += cvtChunk(num%1000000000/1000000);
rst += " Million";
isFirstNonZero = false;
}
if(num%1000000/1000) {
if(!isFirstNonZero) rst += " ";
rst += cvtChunk(num%1000000/1000);
rst += " Thousand";
isFirstNonZero = false;
}
if(num%1000) {
if(!isFirstNonZero) rst += " ";
rst += cvtChunk(num%1000);
isFirstNonZero = false;
}
if(isFirstNonZero) rst = "Zero";
return rst;
}
};