Integer to English Words 整数转换为英语表示

来源:互联网 发布:和英国女人 知乎 编辑:程序博客网 时间:2024/05/22 12:44

Integer to English Words

 

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:

  1. Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
  2. 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.
  3. 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)
class Solution {public://从右向左处理    string numberToWords(int num) {               string ans;        int k=0;        while(num)        {            if(num%1000)                ans = solve(num%1000)+bigs[k]+ans;            k++;            num/=1000;        }        return ans.length()? ans.substr(1):"Zero";//去除第一位前的空格    }        //最多三位数    string solve(int num)    {        string res;        if(num>=100)            res = res + map1[num/100]+" Hundred";        num%=100;                if(num>=10 && num<20)            res += map1[num];        else        {            if(num>19)                res+= map2[num/10];                num%=10;                res+= map1[num];        }        return res;    }    private:    vector<string> map1={"", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve",  " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen"};    vector<string> map2= {"", "", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety"};    vector<string> bigs={"", " Thousand", " Million", " Billion" };    };
0 0