273. 整数转换英文表示

题目描述

将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。

示例 1:

输入: 123
输出: “One Hundred Twenty Three”

示例 2:

输入: 12345
输出: “Twelve Thousand Three Hundred Forty Five”

示例 3:

输入: 1234567
输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”

示例 4:

输入: 1234567891

输出: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”

思路

每三位分成一组,用辅助方法lessHundred来处理每一组的数据。

class Solution {
    private final String[] THOUSAND = {"", "Thousand", "Million", "Billion"};
    private final String[] 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 res = new StringBuilder();
        int index = 0;
        while(num > 0){
            StringBuilder tem = new StringBuilder();
            if(num%1000 != 0){
                lessHundred(num%1000,tem);
                res.insert(0,tem.append(THOUSAND[index]).append(" "));
            }
            num = num/1000;
            index++;
        }
        return res.toString().trim();
    }
    public void lessHundred(int num,StringBuilder tem){
        if(num == 0) return;
        if(num < 20){
            tem.append(TWENTY[num]).append(" ");
        }else if(num < 100){
            tem.append(HUNDRED[num/10]).append(" ");
            lessHundred(num%10,tem);
        }else if(num < 1000){
            tem.append(TWENTY[num/100]).append(" ").append("Hundred").append(" ");
            lessHundred(num%100,tem);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值