假设我们有一个数字。数字可以是0到231 – 1之间的任何数字。我们必须将数字转换为单词。因此,如果数字是512,那么结果将是512。
为了解决这个问题,我们将遵循以下步骤-
定义一些列表,例如less_than_20,它将保存从1到19的所有单词
另一个数组,例如数十个,可容纳数十个,二十个,三十个,以此类推,最多可容纳九十个
数千个数组,可容纳数千,百万和十亿个
定义一个名为的函数helper()
,这将花费n
如果n为0,则返回空白字符串
否则,当n <20时,返回less_than_20 [n] +空白
否则,当n <100时,返回tens [n / 10] +空格+ helper(n mod 10)
否则返回less_than_20 [n / 100] +“一百” +助手(n mod 100)
在主要方法中,执行以下操作
如果num为0,则返回“零”
ans:=空字符串,i:= 0
而num> 0
ans:= helper(num mod 1000)+千[i] +空格+ ans
num:= num / 1000
如果num mod 1000不为0,则
返回ans
让我们看下面的实现以更好地理解-
class Solution(object): less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] tens = ["","Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] thousands = ["", "Thousand", "Million", "Billion"] def numberToWords(self, num): if num == 0: return "Zero" ans = "" i = 0 while num > 0: if num % 1000 != 0: ans = self.helper(num % 1000) + Solution.thousands[i] + " " + ans i += 1 num //= 1000 return ans.strip() def helper(self, n): if n == 0: return "" elif n < 20: return Solution.less_than_20[n] + " " elif n < 100: return Solution.tens[n//10] + " " + self.helper(n % 10) else: return Solution.less_than_20[n // 100] + " Hundred " + self.helper(n % 100) ob = Solution()print(ob.numberToWords(512)) print(ob.numberToWords(7835271))
512 7835271
输出结果
Five Hundred Twelve Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One