本文主要是介绍LeetCode 题解(210) : Integer to English Words,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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)
极其多的边界条件,何处加空格,何处不加空格, 等等等等。
Python版:
class Solution(object):def numberToWords(self, num):""":type num: int:rtype: str"""if num == 0:return "Zero"triples = []while num != 0:triples.append(num % 1000)num /= 1000u = ["", "Thousand", "Million", "Billion"]i = len(triples) - 1result = ""while i >= 0:s = self.tripleToWords(triples[i])if s != "":result += sif i != 0:result += " "result += u[i]if i != 0:result += " "i -= 1result = result.rstrip()return resultdef tripleToWords(self, s):if s == 0:return ""digits = []while s != 0:digits.append(s % 10)s /= 10words = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]tys = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]tens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]result = ""i = len(digits) - 1while i >= 0:if i == 2:result += words[digits[i]] + " Hundred"if digits[i - 1] != 0 or digits[i - 2] != 0:result += " "elif i == 1:if digits[i] == 1:result += tens[digits[i - 1]]breakelse:result += tys[digits[i]]if digits[i - 1] != 0 and digits[i] != 0:result += " "else:result += words[digits[i]]i -= 1return result
这篇关于LeetCode 题解(210) : Integer to English Words的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!