273. Integer to English Words
阿新 • • 發佈:2018-06-17
rep public six ive private amp 一個 eight 來看
問題描述:
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
Example 1:
Input: 123 Output: "One Hundred Twenty Three"
Example 2:
Input: 12345 Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Example 4:
Input: 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
解題思路:
我們可以來看一下0-1 billion之間:
1 0 0 0 0 0 0 0 0 0
billion million thousand hundred
|-----------| |-----------| |------------|
觀察可以發現:每3個0更換一個單位。
我們可以設置一個unit 的hash map,存儲單位,註意0最好也存上相對應的“”
再對1-9, 10-19, 20, 30, 40, 50, 60, 70 ,80, 90進行存儲
對num進行模1000操作取出當前後3位,對後三位進行數文轉換後根據當前技術值count加後面的單位。
需要註意的是:
什麽時候插入空格!
代碼:
class Solution { public: string numberToWords(int num) { unordered_map<int,string> dict ={ {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"}, {20, "Twenty"}, {30, "Thirty"}, {40, "Forty"}, {50, "Fifty"}, {60, "Sixty"}, {70, "Seventy"}, {80, "Eighty"}, {90, "Ninety"} }; unordered_map<int,string> unit = {{0, ""},{1, " Thousand"}, {2, " Million"}, {3," Billion"}}; string ret = ""; int count = 0; if(num == 0) return "Zero"; while(num > 0){ int cur = num % 1000; if(cur != 0){ string wn = toWords(cur, dict); wn += unit[count]; if(ret.size() != 0){ ret = " "+ret; } ret = wn + ret; } count++; num /= 1000; } return ret; } private: string toWords(int n, unordered_map<int, string> &m){ string ret; int h = n/100; if(h != 0) ret = m[h] + " Hundred"; n %= 100; if(n == 0) return ret; if(m.count(n)){ if(ret.size() != 0) ret += " "; ret += m[n]; }else{ int t = n/10; if(t != 0){ if(ret.size() != 0) ret += " "; ret += m[t*10]; } int d = n%10; if(d != 0){ if(ret.size() != 0) ret += " "; ret += m[d]; } } return ret; } };
273. Integer to English Words