[LeetCode] Integer to English Words

简介: This problem is not difficult. But it is not easy to have a bug-free code. As you write your codes according to the hints, the most important thing is...

This problem is not difficult. But it is not easy to have a bug-free code. As you write your codes according to the hints, the most important thing is to handle all the edge cases without making the code ugly :-) Well, the key to simplify the code is to us hard coding. This link provides a nice solution, whose Java code is rewritten below in C++. Since C++ has no convenient functions like trim and I do not want to create one on my own, I handle the " " and ' ' carefully using some tricks from this link (for example, I include the space in the words of the numbers).

 1 class Solution {
 2 public: 
 3     string numberToWords(int num) {
 4         vector<string> bigs = { "", " Thousand", " Million", " Billion" };
 5         int i = 0;
 6         string ans;
 7         while (num) {
 8             if (num % 1000) ans = numberWords(num % 1000) + bigs[i] + ans;
 9             i++, num /= 1000;
10         }
11         return ans.length() ? ans.substr(1) : "Zero";
12     }
13 private:
14     string numberWords(int num) {
15         char* one[] = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine" };
16         char* ones[] = { " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen" };
17         char* tens[] = { "", "", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety" };
18         string ans;
19         if (num > 99) ans += string(one[num / 100]) + " Hundred";
20         num %= 100;
21         if (num > 9 && num < 20) ans += ones[num % 10];
22         else {
23             if (num > 19) ans += tens[num / 10];
24             num %= 10;
25             if (num) ans += one[num];
26         }
27         return ans;
28     }
29 };

 

目录
相关文章
|
索引 Python
LeetCode 820. 单词的压缩编码 Short Encoding of Words
LeetCode 820. 单词的压缩编码 Short Encoding of Words
LeetCode 273. Integer to English Words
将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
36 0
LeetCode 273. Integer to English Words
|
Java 索引 Python
LeetCode 151:给定一个字符串,逐个翻转字符串中的每个单词 Reverse Words in a String
公众号:爱写bug(ID:icodebugs) 翻转字符串里的单词 Given an input string, reverse the string word by word. 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
1557 0