0273.cpp (1497B)
1 class Solution { 2 static string int_string(int n) { 3 static const char *const below_20[] = {"One", "Two", "Three", "Four", "Five", 4 "Six", "Seven", "Eight", "Nine", "Ten", 5 "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", 6 "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; 7 static const char *const below_100[] = {"Twenty", "Thirty", "Forty", "Fifty", 8 "Sixty", "Seventy", "Eighty", "Ninety"}; 9 10 if (n >= 1000000000) 11 return int_string(n / 1000000000) + " Billion" + int_string(n - 1000000000 * (n / 1000000000)); 12 else if (n >= 1000000) 13 return int_string(n / 1000000) + " Million" + int_string(n - 1000000 * (n / 1000000)); 14 else if (n >= 1000) 15 return int_string(n / 1000) + " Thousand" + int_string(n - 1000 * (n / 1000)); 16 else if (n >= 100) 17 return int_string(n / 100) + " Hundred" + int_string(n - 100 * (n / 100)); 18 else if (n >= 20) 19 return string(" ") + below_100[n / 10 - 2] + int_string(n - 10 * (n / 10)); 20 else if (n >= 1) 21 return string(" ") + below_20[n - 1]; 22 23 return ""; 24 } 25 26 public: 27 string numberToWords(int num) const { 28 if (num == 0) return "Zero"; 29 return int_string(num).substr(1); 30 } 31 };