​LeetCode刷题实战273:整数转换英文表示

程序IT圈

共 3883字,需浏览 8分钟

 ·

2021-05-29 07:18

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 整数转换英文表示,我们先来看题面:
https://leetcode-cn.com/problems/integer-to-english-words/
Convert a non-negative integer num to its English words representation.
将非负整数 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"


解题


这个是网上比较好理解的了 。

class Solution {
    private final String[] THOUSAND = {"", "Thousand", "Million", "Billion"};
    private final String[] LESS_THAN_TWENTY = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private final String[] HUNDRED = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    public String numberToWords(int num) {
        if(num == 0) return "Zero";

        StringBuilder sb = new StringBuilder();
        int index = 0;
        while(num > 0) {
            if(num % 1000 != 0) {
                StringBuilder tmp = new StringBuilder();
                helper(num % 1000, tmp);
                sb.insert(0, tmp.append(THOUSAND[index]).append(" "));
            }
            index++;
            num /= 1000;
        }
        return sb.toString().trim();
    }

    private void helper(int num, StringBuilder tmp) {
        if(num == 0) return;
        if(num < 20) {
            tmp.append(LESS_THAN_TWENTY[num]).append(" ");
        }else if(num < 100) {
            tmp.append(HUNDRED[num / 10]).append(" ");
            helper(num % 10, tmp);
        }else {
            tmp.append(LESS_THAN_TWENTY[num / 100]).append(" Hundred").append(" ");
            helper(num % 100, tmp);
        }
    }
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-260题汇总,希望对你有点帮助!
LeetCode刷题实战261:以图判树
LeetCode刷题实战262:行程和用户
LeetCode刷题实战263:丑数
LeetCode刷题实战264:丑数 II
LeetCode刷题实战265:粉刷房子II
LeetCode刷题实战266:回文排列
LeetCode刷题实战267:回文排列II
LeetCode刷题实战268:丢失的数字
LeetCode刷题实战269:火星词典
LeetCode刷题实战270:最接近的二叉搜索树值


浏览 26
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报