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)
這道題讓我們把一個整型數轉為用英文單詞描述,就像在check上寫錢數的方法,我最開始的方法特別復雜,因為我用了幾個switch語句來列出所有的單詞,但是我看網上大神們的解法都是用數組來枚舉的,特別的巧妙而且省地方,膜拜學習中。題目中給足了提示,首先告訴我們要3個一組的進行處理,而且題目中限定了輸入數字范圍為0到231 - 1之間,最高只能到billion位,3個一組也只需處理四組即可,那么我們需要些一個處理三個一組數字的函數,我們需要把1到19的英文單詞都列出來,放到一個數組里,還要把20,30,... 到90的英文單詞列出來放到另一個數組里,然后我們需要用寫技巧,比如一個三位數n,百位數表示為n/100,后兩位數一起表示為n%100,十位數表示為n%100/10,個位數表示為n%10,然后我們看后兩位數是否小於20,小於的話直接從數組中取出單詞,如果大於等於20的話,則分別將十位和個位數字的單詞從兩個數組中取出來。然后再來處理百位上的數字,還要記得加上Hundred。主函數中調用四次這個幫助函數,然后中間要插入"Thousand", "Million", "Billion"到對應的位置,最后check一下末尾是否有空格,把空格都刪掉,返回的時候檢查下輸入是否為0,是的話要返回'Zero'。參見代碼如下:
class Solution { public: string numberToWords(int num) { string res = convertHundred(num % 1000); vector<string> v = {"Thousand", "Million", "Billion"}; for (int i = 0; i < 3; ++i) { num /= 1000; res = num % 1000 ? convertHundred(num % 1000) + " " + v[i] + " " + res : res; } while (res.back() == ' ') res.pop_back(); return res.empty() ? "Zero" : res; } string convertHundred(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", "Eighty", "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; } };
參考資料:
https://leetcode.com/discuss/55268/short-clean-c-code-with-explanation
LeetCode All in One 題目講解匯總(持續更新中...)