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)
Solution:
The solution is very straight forward, but need to take care of space between words and at the end of the sentence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string numberToWords(int num) { | |
string LESS_THAN_20[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; | |
string TENS[] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; | |
string THOUSANDS[] = {"", "Thousand", "Million", "Billion"}; | |
string res; | |
int thousands=0; | |
int tens=0; | |
int l20s=0; | |
if(num==0) | |
return string("Zero"); | |
while(num!=0){ | |
int digits=num%1000; | |
num=num/1000; | |
if(digits==0){ | |
thousands++; | |
continue; | |
} | |
int hundreds=digits/100; | |
int tens=(digits%100)/10; | |
int ones=digits%10; | |
string substr; | |
if(tens<2) | |
substr = LESS_THAN_20[tens*10+ones]; | |
else | |
substr = TENS[tens] + string(" ") + LESS_THAN_20[ones]; | |
if(hundreds!=0) | |
substr = LESS_THAN_20[hundreds] + string(" ") + string("Hundred") + string(" ") + substr; | |
substr=substr[substr.length()-1]==' '? substr.substr(0, substr.length()-1):substr; | |
res=thousands==0? substr:substr + string(" ") + THOUSANDS[thousands] + string(" ")+ res; | |
res=res[res.length()-1]==' '? res.substr(0, res.length()-1):res; | |
thousands++; | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment