前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >整数转英文表示

整数转英文表示

作者头像
zucchiniy
发布2020-05-22 14:41:00
1.4K0
发布2020-05-22 14:41:00
举报
文章被收录于专栏:洞明学问洞明学问

将非负整数转换为其对应的英文表示。 LeetCode数转换英文表示

class Solution:
    def numberToWords(self, num: int) -> str:
       one_to_19 = '''One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve
               Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'''.split()
       tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()

       def helper(num):
           if num < 20:
               return one_to_19[num - 1:num]
           elif num < 100:
               return [tens[num // 10 - 2]] + helper(num % 10)
           elif num < 1000:
               return [one_to_19[num // 100 -1]] + ['Hundred'] + helper(num % 100)

           for p,w in enumerate(['Thousand','Million','Billion'],1):
               if num < 1000 ** (p+1):
                   return helper(num//1000**p) + [w] + helper(num % 1000 ** p)

        return ' '.join(helper(num)) or "Zero"

这里做了两个测试,关于 if-elifif...if 的时间,在 Leetcode 上测试的时候,发现 if-elif 的效率是低于两个 if...if 的效率的,具体时候如下:

所以在没有具体的逻辑要求的时候,使用 if...if 代替 if-elif 来提高效率,但是为什么会与我的认知相反呢?很奇怪,有时间希望可以研究一下两个的时间使用效率的差别。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档