阅读 200

leetcode每日一题系列-整数转换英文表示-「英文水平」

leetcode-273-整数转换英文表示

[博客链接]

菜????的学习之路

掘金首页

[题目链接]

题目链接

[github地址]

github地址

[题目描述]

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

 

示例 1:

输入:num = 123 输出:"One Hundred Twenty Three" 复制代码

示例 2:

输入:num = 12345 输出:"Twelve Thousand Three Hundred Forty Five" 复制代码

示例 3:

输入:num = 1234567 输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" 复制代码

示例 4:

输入:num = 1234567891 输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" 复制代码

提示:

  • 0 <= num <= 2312^{31}231 - 1

思路一:英文水平

  • 大家就当来复习英文水平就好了

  • 因为这道题感觉真的没啥考察价值虽然是道hard

  • 但是英文不行哪怕他是easy也做不出来

  • 999为一组,然后注意特殊的证书1-20 其余的就没啥了

  • 枚举拼接即可

class Solution {     static String[] num2str_small = {         "Zero",          "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",          "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"     };     static String[] num2str_medium = {         "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"     };     static String[] num2str_large = {         "Billion", "Million", "Thousand", "",     };     String num2Str(int x) {         String ans = "";         if (x >= 100) {             ans += num2str_small[x / 100] + " Hundred ";             x %= 100;         }         if (x >= 20) {             ans += num2str_medium[x / 10] + " ";             x %= 10;         }         if (x != 0) ans += num2str_small[x] + " ";         return ans;     }     public String numberToWords(int num) {         if (num == 0) return num2str_small[0];         StringBuilder sb = new StringBuilder();         for (int i = (int)1e9, j = 0; i >= 1; i /= 1000, j++) {             if (num < i) continue;             sb.append(num2Str(num / i) + num2str_large[j] + " ");             num %= i;         }         while (sb.charAt(sb.length() - 1) == ' ') sb.deleteCharAt(sb.length() - 1);         return sb.toString();     } } 复制代码

  • ps:这里用的三叶大佬的代码,我写这种代码丑陋的过分,还是用三叶的看着舒服

  • 时间复杂度O(n)



作者:saberlgy
链接:https://juejin.cn/post/7017678426177798152

文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐