LeetCode #273: Integer to English Words

129 篇文章 0 订阅

Problem Statement

(Source) Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2311 .

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值