【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]

 

posted @ 2018-12-31 21:28  seyjs  阅读(170)  评论(0编辑  收藏  举报