Monday, November 9, 2015

Leetcode: Integer to English Words

Difficulty: Medium


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)

--------------------------------------------------------
-------------------------------------------------------

According to the hints, the core is to build the help function to transfer three digits into a string. In general, there are three kinds of words for all 3-digits:

"Hundred";

 "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "

"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety ";

with above words, we can build all strings for 3-digits in English. 

////////////////////////////////////////
//codes
class Solution {
 public:
        string hundred2Eng(int val){
               vector<string> v1 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
               vector<string> v2 = { "", "", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
               int hund = val / 100, ten = val % 100, dig = ten % 10;
               string res = ten<20 ? (v1[ten]) : (v2[ten / 10] + v1[dig]);
               string hud = hund == 0 ? "" : "Hundred ";
               res = v1[hund] + hud + res;
               return res;
        }

        string numberToWords(int num) {
               //check input
               if (num == 0)return "Zero";

               vector<string> v = { "Thousand ", "Million ", "Billion " };
               string res = hundred2Eng(num % 1000), tmp;
               num = num / 1000;
               for (int i = 0; i<3; i++){
                      if (num % 1000 != 0)tmp = hundred2Eng(num % (1000)) + v[i] + tmp;
                      num = num / 1000;
               }
               res = tmp + res;
               res.pop_back();//remove the final " ".
               return res;
        }
 };




No comments:

Post a Comment