1. 程式人生 > >【leetcode】273. Integer to English Words

【leetcode】273. Integer to English Words

題目如下:

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

解題思路:這種題目本身沒什麼難度,就是繁瑣。我的解法是 Input 倒序遍歷,每三個數字一組,算出對應的英文表達方式,同時加上 Thousand/Million/Billion。

程式碼如下:

class Solution(object):
    def convert(self,v):
        units 
= ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'] e_units = ['Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']
if len(v) == 1: return units[int(v)] elif len(v) == 2 and int(v) >= 11 and int(v) <= 19: return e_units[int(v)-11] elif len(v) == 3 and int(v[1:]) >= 11 and int(v[1:]) <= 19: h = (units[int(v[0])] + ' Hundred ') if int(v[0]) != 0 else '' return h + e_units[int(v[1:]) - 11] tv = '' v = int(v) count = 0 while v > 0: remainder = v % 10 if count == 0: tv = units[remainder] + ' ' + tv elif count == 1: tv = tens[int(remainder)] + ' ' + tv else: tv = 'Hundred' + ' ' + tv tv = units[int(remainder)] + ' ' + tv count += 1 v = v / 10 return tv def numberToWords(self, num): """ :type num: int :rtype: str """ if num == 0: return 'Zero' num = str(num) t_units = ['','Thousand','Million','Billion'] res = '' v = '' count = 0 for i in num[::-1]: v = i + v if len(v) == 3: cv = self.convert(v) if len(cv) > 0: res = cv + ' ' + t_units[count] + ' ' + res v = '' count += 1 if len(v) > 0: res = self.convert(v) + ' ' + t_units[count] + ' ' + res trim = '' last = None # 下面所有的程式碼都是為了去掉多餘的空格 for i in res: if last == None: last = i trim += i elif i == ' ' and last == ' ': continue else: trim += i last = i return trim[:len(trim)-1]