LeetCode #273: Integer to English Words
来源:互联网 发布:服装网络推广方案 编辑:程序博客网 时间:2024/04/30 00:27
Problem Statement
(Source) Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than
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”
Analysis
Split the input number into groups of 3 digits from lowest bit to highest bit. Then process each group and add corresponding units to the result of each group. Combine sub-answer to get the final global answer.
Solution
class Solution(object): def process(self, map1, map2, num): """Process a non-negtive number which contains no more than 3 digits. """ if num == 0: return '' elif num < 20: return map1[num] elif num >= 20 and num <= 99: ans = map2[num / 10] if num % 10: ans = ans + ' ' + map1[num % 10] return ans else: ans = map1[num / 100] + ' Hundred' if num % 100: ans = ans + ' ' + self.process(map1, map2, num % 100) return ans def numberToWords(self, num): """ :type num: int :rtype: str """ if num == 0: return 'Zero' res = [] map1 = {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'} map2 = {2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'} unit_map = {1: 'Thousand', 2: 'Million', 3: 'Billion'} unit = 0 while num: x = num % 1000 sub_ans = self.process(map1, map2, x) if sub_ans: if unit: sub_ans = sub_ans + ' ' + unit_map[unit] res.append(sub_ans) num /= 1000 unit += 1 res.reverse() return ' '.join(res)
0 0
- [leetcode-273]Integer to English Words(java)
- [leetcode 273]Integer to English Words
- leetcode 273: Integer to English Words
- leetcode 273 : Integer to English Words
- LeetCode 273 Integer to English Words
- LeetCode 273 Integer to English Words
- LeetCode #273: Integer to English Words
- leetcode - Integer to English Words
- [leetcode] Integer to English Words
- Integer to English Words -- leetcode
- [LeetCode] Integer to English Words
- LeetCode -- Integer to English Words
- 【LeetCode】Integer to English Words
- LeetCode Integer to English Words
- Leetcode: Integer to English Words
- leetcode:Integer to English Words
- 【LeetCode】Integer to English Words
- [273]Integer to English Words
- 如何才能优雅的撸代码-----你知道sublime,nodepad++和webstorm么?
- Android开发——BaseAdapter的使用
- Android Service的生命周期
- 编译boost 1.58.0 for arm-linux
- 【OpenCV】人脸识别——识别是谁
- LeetCode #273: Integer to English Words
- Qt tips 如何给Qlabel添加clicked属性
- Airbnb 資深工程師分享:怎樣才是正確、有效的 code review
- ActiveMQ入门笔记(1)
- Solaris10上安装Redis3.0.6
- 护照识别技术提高信息采集效率
- shell 抽象变量
- AndroidStudio使用git上传项目到github
- Go起步:7、流程控制