LeetCode273——整数转换英文表示

本博客主要介绍LeetCode第273题,即如何将整数转化为英文表示。通过分区间递归解决,详细解释了思路并提供了JAVA代码实现。涉及知识点包括数学和递归。
摘要由CSDN通过智能技术生成

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/integer-to-english-words/

题目描述:

知识点:数学

思路:分区间递归求解

(1)首先,按千来划分,[0, 999],[1000, 999999],[1000000, 999999999],[1000000000, 2 ^ 31 - 1]。

(2)其次,对小于1000的数求得其英文表示,求解过程利用了递归的思想。

时间复杂度和具体数字有关,不好分析。空间复杂度是O(1)。

JAVA代码:

public class Solution {
    private static final String[] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
            "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
            "Seventeen", "Eighteen", "Nineteen"};
    private static final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
            "Seventy", "Eighty", "Ninety"};
    private static final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
    public String numberToWords(int num) {
        if (0 == num) {
            return "Zero";
        }
        int i = 0;
        String result = "";
        while (0 < num) {
            if (0 != num % 1000) {
                result = helper(num % 1000) + THOUSANDS[i] + " " + result;
            }
            num /= 1000;
            i++;
        }
        return result.trim();
    }
    private String helper(int num) {
        if (0 == num) {
            return "";
        } else if (20 > num) {
            return LESS_THAN_20[num] + " ";
        } else if (100 > num) {
            return TENS[num / 10] + " " + helper(num % 10);
        } else {
            return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
        }
    }
}

LeetCode解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值