[CareerCup] 17.7 English Phrase Describe Integer 英文单词表示数字
17.7 Given any integer, print an English phrase that describes the integer (e.g., "One Thousand, Two Hundred Thirty Four").
LeetCode上的原题,请参见我之前的博客Integer to English Words。
string convert_hundred(int num) { 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", "Eigthy", "Ninety"}; string res; int a = num / 100, b = num % 100, c = num % 10; res = b < 20 ? v1[b] : v2[b / 10] + (c ? " " + v1[c] : ""); if (a > 0) res = v1[a] + " Hundred" + (b ? " " + res : ""); return res; } string num_to_string(int num) { if (num < 0) return "Negative " + num_to_string(-1 * num); vector<string> v = {"Thousand", "Million", "Billion"}; string res = convert_hundred(num % 1000); for (int i = 0; i < 3; ++i) { num /= 1000; res = num % 1000 ? convert_hundred(num % 1000) + " " + v[i] + " " + res : res; } while (res.back() == ' ') res.pop_back(); return res; }